<?php
namespace App\Controller;
use finfo;
use App\Entity\Contacts;
use App\Service\Securizer;
use App\Repository\ClientsRepository;
use App\Repository\ContactsRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class ContactController extends AbstractController
{
/**
* @IsGranted("ROLE_USER")
*/
public function index(ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir la liste de tous les contacts
$securizer = new Securizer($accessDecisionManager);
$contacts = $repoContact->findContactTous($this->getUser(), $securizer);
return $this->json($contacts, 200, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function actif(ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir la liste des contacts actif
$securizer = new Securizer($accessDecisionManager);
$contacts = $repoContact->findContactActif($this->getUser(), $securizer);
return $this->json($contacts, 200, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function actifList(ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//lister nom, prenom et id de contacts actif
$contacts = $repoContact->findBy(["archive" => 0]);
return $this->json($contacts, 200, [], ['groups' => 'affichageContactList']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function archiver(ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir la liste des contacts archivé
$securizer = new Securizer($accessDecisionManager);
$contacts = $repoContact->findContactArchiver($this->getUser(), $securizer);
return $this->json($contacts, 200, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function tech(ContactsRepository $repoContact): Response
{
//voir la liste des contacts avec le role commercial
$contactsActif = $repoContact->findBy(['archive' => false]);
$contacts = [];
foreach ($contactsActif as $contact) {
if (in_array("ROLE_TECH", $contact->getRoles()))
array_push($contacts, $contact);
}
return $this->json(
$contacts,
200,
['Cache-Control' => 'max-age=86400'],
['groups' => 'affichageContact']
);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function commercial(ContactsRepository $repoContact): Response
{
//voir la liste des contacts avec le role tech
$contactsActif = $repoContact->findBy(['archive' => false]);
$contacts = [];
foreach ($contactsActif as $contact) {
if (in_array("ROLE_COMMERCIAL", $contact->getRoles()))
array_push($contacts, $contact);
}
return $this->json(
$contacts,
200,
['Cache-Control' => 'max-age=86400'],
['groups' => 'affichageContact']
);
}
/**
* @IsGranted("ROLE_USER")
*/
public function avatarContact(Request $request): Response
{
//le dossier de destination du fichier telecharger
$destination = $this->getParameter('kernel.project_dir') . '/public/img/avatar_contact';
//le fichier lelecharger
$img = $request->files->get("myFile");
//tester le type de fichier envoyer par l'utilisateur
// test de l'extension, pas suffisant il faut tester le type MINE du fichier
//tableau des extention acceptées
$extensions = array('.png', '.gif', '.jpg', '.jpeg');
//recuperation de l'extention du fichier
$extension = strrchr($_FILES['myFile']['name'], '.');
//renvoie un json d'erreur si l'extension du fichier n'est pas dans le tableau
if (!in_array($extension, $extensions)) {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez uploder que des fichiers de type .png, .gif, .jpeg, .jpg"
], 400);
}
//test du type MINE
//tableau des type MINE accepter
$mineTypes = array('image/png', 'image/gif', 'image/jpg', 'image/jpeg');
//retourne le type MINE
$finfo = new finfo(FILEINFO_MIME_TYPE, NULL);
$fileMineType = $finfo->file($_FILES['myFile']['tmp_name']);
//renvoie un json d'erreur si le MINE type n'est pas dans le tableau
if (!in_array($fileMineType, $mineTypes)) {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez uploder que des fichiers de type .png, .gif, .jpeg, .jpg"
], 400);
}
//renomage du fichier pour qu'il soit unique sur la serveur
$newFilename = uniqid() . '-' . $img->getClientOriginalName();
//enregistrement du fichier dans le dossier de destination
$img->move($destination, $newFilename);
//json de retour pour envoi de l'url en base
return $this->json(
[
'status' => 200,
'url' => 'img' . '/avatar_contact/' . $newFilename
],
200,
['Cache-Control' => 'max-age=86400']
);
}
/**
* @IsGranted("ROLE_USER")
*/
public function voir($id, ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir les details d'un contact par id
$securizer = new Securizer($accessDecisionManager);
$contacts = $repoContact->findContactTous($this->getUser(), $securizer);
//verifi que le contact que l'on cherche fait bien partie de la liste de ceux qu'il est possible d'afficher
if (in_array($repoContact->find($id), $contacts)) {
$contact = $repoContact->find($id);
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter ce contact"
], 400);
}
return $this->json($contact, 200, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function searchContact($search, ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
$contacts = $repoContact->globalSearch($search, $this->getUser(), $securizer);
return $this->json($contacts, 200, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function creer(
Request $request,
ValidatorInterface $validator,
SerializerInterface $serializer,
ContactsRepository $contactsRepo,
EntityManagerInterface $manager,
ClientsRepository $repoClient,
AccessDecisionManagerInterface $accessDecisionManager
): Response {
//creer un nouveau contact, seul les role client ou superieur peuvent acceder
$securizer = new Securizer($accessDecisionManager);
$user = $this->getUser();
$clients = $repoClient->findClientActif($user, $securizer);
$jsonRecu = $request->getContent();
try {
$jsonRecu = json_decode($jsonRecu);
if (!isset($jsonRecu->mail) || empty($jsonRecu->mail)) {
$contacts = $contactsRepo->findAll();
$jsonRecu->mail = 'nomail' . count($contacts) . '@exist.fr';
}
$jsonRecu = json_encode($jsonRecu);
//transforme le json reçu en entity
$contact = $serializer->deserialize($jsonRecu, Contacts::class, 'json');
//interdit la creation d'un client avec role superieur au sien
$creationPossible = true;
foreach ($contact->getRoles() as $role) {
if (!$securizer->isGranted($user, $role)) {
$creationPossible = false;
break;
}
}
//verifi que le role que l'on souhaite donné au nouveau contact est bien inferieur a celui de l'utilisateur
if ($creationPossible) {
//verifi que le client au quel on souhaite lier le nouveau contact fait bien partie de la liste de ceux qu'il est possible d'afficher
if (in_array($contact->getIdClient(), $clients)) {
$contact->setRoles(["ROLE_USER"])->setPassword('12345');
$errors = $validator->validate($contact);
if (count($errors) > 0) {
return $this->json($errors, 400);
}
$manager->persist($contact);
$manager->flush();
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas lier un contact à ce client"
], 400);
}
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas donner ce rôle"
], 400);
}
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($contact, 201, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function modif($id, Request $request, ContactsRepository $repoContact, ValidatorInterface $validator, SerializerInterface $serializer, EntityManagerInterface $manager, ClientsRepository $repoClient, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//modifi un contact existant, seul les role client ou superieur peuvent acceder a cette page
$securizer = new Securizer($accessDecisionManager);
$user = $this->getUser();
$clients = $repoClient->findClientTous($this->getUser(), $securizer);
$contacts = $repoContact->findContactTous($this->getUser(), $securizer);
//verifi que le contact que l'on cherche fait bien partie de la liste de ceux qu'il est possible d'afficher
if (in_array($repoContact->find($id), $contacts)) {
$contact = $repoContact->find($id);
} else {
return $this->json([
//retourne un json avec message d'erreur si l'on a pas le droit d'afficher ou si l'id n'existe pas
'status' => 400,
'message' => "Vous ne pouvez pas acceder a ce contact"
], 400);
}
$jsonRecu = $request->getContent();
try {
//transforme le json reçu en entity
$serializer->deserialize($jsonRecu, Contacts::class, 'json', ['object_to_populate' => $contact]);
//interdit la creation d'un client avec role superieur au sien
$creationPossible = true;
foreach ($contact->getRoles() as $role) {
if (!$securizer->isGranted($user, $role)) {
$creationPossible = false;
break;
}
}
//verifi que le role que l'on souhaite donné au nouveau contact est bien inferieur a celui de l'utilisateur
if ($creationPossible) {
//verifi que le client au quel on souhaite lier le nouveau contact fait bien partie de la liste de ceux qu'il est possible d'afficher
if (in_array($contact->getIdClient(), $clients)) {
$errors = $validator->validate($contact);
if (count($errors) > 0) {
return $this->json($errors, 400);
}
$manager->persist($contact);
$manager->flush();
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas lier un contact à ce client"
], 400);
}
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas donner ce rôle"
], 400);
}
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($contact, 201, [], ['groups' => 'affichageContact']);
}
/**
* @IsGranted("ROLE_USER")
*/
public function getContactsByClient($idClient, ContactsRepository $repoContact, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$contacts = $repoContact->findBy(['idClient' => $idClient]);
$securizer = new Securizer($accessDecisionManager);
// Si le utilisateur n'est pas ROLE_TECH retourne la liste seulement si il apartient au client
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH")) {
$contact = $repoContact->findOneBy(["mail" => $this->getUser()->getUserIdentifier()]);
if ($contact->getIdClient()->getId() != $idClient)
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter ce contact"
], 400);
}
return $this->json($contacts, 200, [], ['groups' => 'affichageContact']);
}
}