src/Controller/ElementsParkController.php line 321

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\Securizer;
  4. use App\Entity\ElementsPark;
  5. use App\Entity\TypesElementPark;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use App\Repository\ElementsParkRepository;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use App\Repository\TypesElementParkRepository;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use App\Repository\CategoriesElementRepository;
  12. use DateTime;
  13. use Symfony\Component\Serializer\SerializerInterface;
  14. use Symfony\Component\Validator\Validator\ValidatorInterface;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  18. use Symfony\Component\Validator\Constraints\Date;
  19. class ElementsParkController extends AbstractController
  20. {
  21.     /**
  22.      * @IsGranted("ROLE_TECH")
  23.      */
  24.     public function index(int $idClientElementsParkRepository $repoElement): Response
  25.     {
  26.         //liste tous les elements de parc qu'il est possible d'afficher
  27.         $elements $repoElement->findElementsPark($idClient);
  28.         return $this->json($elements200, [], ['groups' => 'affichageElement']);
  29.     }
  30.     /**
  31.      * @IsGranted("ROLE_TECH")
  32.      */
  33.     public function voir($idClient$idElementElementsParkRepository $repoElement): Response
  34.     {
  35.         $elements $repoElement->findElementsPark($idClient);
  36.         for ($i 0$i count($elements); $i++) {
  37.             if ($elements[$i]['id'] == (int)$idElement$element $elements[$i];
  38.         }
  39.         if (isset($element))
  40.             return $this->json($element200, [], ['groups' => 'affichageElement']);
  41.         else
  42.             return $this->json([
  43.                 'status' => 400,
  44.                 'message' => 'L’objet n’appartient pas au parc sélectionné'
  45.             ], 400);
  46.     }
  47.     /**
  48.      * @IsGranted("ROLE_TECH")
  49.      */
  50.     public function getArchive(int $idClientElementsParkRepository $repoElement): Response
  51.     {
  52.         //liste tous les elements de parc qu'il est possible d'afficher
  53.         $elements $repoElement->findElementsPark($idClienttrue);
  54.         return $this->json($elements200, [], ['groups' => 'affichageElement']);
  55.     }
  56.     /**
  57.      * @IsGranted("ROLE_TECH")
  58.      */
  59.     public function creer(Request $requestValidatorInterface $validatorSerializerInterface $serializerEntityManagerInterface $manager): Response
  60.     {
  61.         // Creer un nouvel élément de park, seul les roles tech et admin peuvent accer a cette url
  62.         $jsonRecu $request->getContent();
  63.         try {
  64.             //transforme le json reçu en entity
  65.             $element $serializer->deserialize($jsonRecuElementsPark::class, 'json');
  66.             //validation des données reçus
  67.             $errors $validator->validate($element);
  68.             if (count($errors) > 0) {
  69.                 return $this->json($errors400);
  70.             }
  71.             $manager->persist($element);
  72.             $manager->flush();
  73.         } catch (\throwable $e) {
  74.             return $this->json([
  75.                 'status' => 400,
  76.                 'message' => $e->getMessage()
  77.             ], 400);
  78.         }
  79.         return $this->json($element201, [], ['groups' => 'affichageElement']);
  80.     }
  81.     /**
  82.      * @IsGranted("ROLE_TECH")
  83.      */
  84.     public function uploadFile(Request $requestEntityManagerInterface $managerElementsParkRepository $repoElementAccessDecisionManagerInterface $accessDecisionManager): Response
  85.     {
  86.         // charger un fichier a un élément de park, seul les roles tech ou supperieur peuvent accer a cette url
  87.         $securizer = new Securizer($accessDecisionManager);
  88.         if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
  89.             return $this->json([
  90.                 'status' => 400,
  91.                 'message' => "Vous ne pouvez pas consulter cet élément"
  92.             ], 400);
  93.         try {
  94.             $file $request->files->get('myFile');
  95.             // ** Vérifier si les dossiers existes et si oui supprimer le contenu
  96.             $path dirname(__DIR__) . '/../documents/parc/client_' $_POST["clientId"] . "/";
  97.             if (!is_dir($path))
  98.                 mkdir($path0777true);
  99.             // ** Télécharger le fichier
  100.             if (!empty($file)) {
  101.                 $file->move(
  102.                     $path,
  103.                     $_FILES["myFile"]["name"]
  104.                 );
  105.             }
  106.             $entity $repoElement->find($_POST["elementId"]);
  107.             $update $entity->getData();
  108.             if (!isset($update["files"]))
  109.                 $update["files"] = [];
  110.             array_push($update["files"], $_FILES["myFile"]["name"]);
  111.             $entity->setData($update);
  112.             $manager->persist($entity);
  113.             $manager->flush();
  114.         } catch (\throwable $e) {
  115.             return $this->json([
  116.                 'status' => 400,
  117.                 'message' => $e->getMessage()
  118.             ], 400);
  119.         }
  120.         return $this->json($entity201, [], ['groups' => 'affichageElement']);
  121.     }
  122.     /**
  123.      * @IsGranted("ROLE_TECH")
  124.      */
  125.     public function getFile($dataAccessDecisionManagerInterface $accessDecisionManager)
  126.     {
  127.         // télécharger un fichier d'un élément de parc, seul les roles tech ou supperieur peuvent accer a cette url
  128.         $securizer = new Securizer($accessDecisionManager);
  129.         if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
  130.             return $this->json([
  131.                 'status' => 400,
  132.                 'message' => "Vous ne pouvez pas consulter cet élément"
  133.             ], 400);
  134.         try {
  135.             $path =  dirname(__DIR__) . "/../documents/parc/client_" str_replace("::filename""/"str_replace("::extension""."$data));
  136.             if (!is_file($path))
  137.                 return $this->json([
  138.                     'status' => 400,
  139.                     'message' => "Aucun fichier de ce type n’a été trouvé"
  140.                 ], 400);
  141.         } catch (\throwable $e) {
  142.             return $this->json([
  143.                 'status' => 400,
  144.                 'message' => $e->getMessage()
  145.             ], 400);
  146.         }
  147.         // header('Access-Control-Allow-Origin: ' . "http://localhost:8001");
  148.         header('Access-Control-Allow-Origin: ' "https://extranet.cco-info.fr/");
  149.         header('Access-Control-Allow-Credentials: true');
  150.         header('Access-Control-Allow-Methods: POST');
  151.         header('Access-Control-Allow-Headers: Content-Type');
  152.         header('Content-Description: File Transfer');
  153.         header('Content-Type: application/octet-stream');
  154.         header('Content-Disposition: attachment; filename="' basename($path) . '"');
  155.         header('Expires: 0');
  156.         header('Cache-Control: must-revalidate');
  157.         header('Pragma: public');
  158.         header('Content-Length: ' filesize($path));
  159.         flush(); // Flush system output buffer
  160.         echo readfile($path);
  161.     }
  162.     /**
  163.      * @IsGranted("ROLE_TECH")
  164.      */
  165.     public function deleteFile($dataint $idElementsParkRepository $repoElementEntityManagerInterface $managerAccessDecisionManagerInterface $accessDecisionManager): Response
  166.     {
  167.         // permets de effacer un fichier d'un element de parc
  168.         $securizer = new Securizer($accessDecisionManager);
  169.         if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
  170.             return $this->json([
  171.                 'status' => 400,
  172.                 'message' => "Vous ne pouvez pas consulter cet élément"
  173.             ], 400);
  174.         try {
  175.             $entity $repoElement->find($id);
  176.             $fileName str_replace("::extension""."explode("::filename"$data)[1]);
  177.             $path =  dirname(__DIR__) . "/../documents/parc/client_" $entity->getIdClient()->getId() . "/" str_replace("::filename""/"str_replace("::extension""."$data));
  178.             if (!is_file($path))
  179.                 return $this->json([
  180.                     'status' => 400,
  181.                     'message' => "Aucun fichier de ce type n’a été trouvé"
  182.                 ], 400);
  183.             unlink($path);
  184.             $update $entity->getData();
  185.             array_splice($update["files"], array_search($fileName$update["files"]), 1);
  186.             $entity->setData($update);
  187.             $manager->persist($entity);
  188.             $manager->flush();
  189.         } catch (\throwable $e) {
  190.             return $this->json([
  191.                 'status' => 400,
  192.                 'message' => $e->getMessage()
  193.             ], 400);
  194.         }
  195.         return $this->json(true201);
  196.     }
  197.     /**
  198.      * @IsGranted("ROLE_TECH")
  199.      */
  200.     public function modif($idElementRequest $requestElementsParkRepository $repoElementTypesElementParkRepository $repoTypesSerializerInterface $serializerValidatorInterface $validatorEntityManagerInterface $manager): Response
  201.     {
  202.         //modifi un élément existant, seul les roles tech et plus peuvent acceder a cette url
  203.         $element $repoElement->find($idElement);
  204.         $idClientDepart $element->getIdClient()->getId();
  205.         if ($element == null) {
  206.             return $this->json([
  207.                 'status' => 400,
  208.                 'message' => "l'élément à modifier n'existe pas"
  209.             ], 400);
  210.         }
  211.         try {
  212.             if ($element->getIdClient()->getId() == $idClientDepart) {
  213.                 $json $request->getContent();
  214.                 $serializer->deserialize($jsonElementsPark::class, 'json', ['object_to_populate' => $element]);
  215.                 $json json_decode($json);
  216.                 if (isset($json->idCategory)) {
  217.                     $element->setIdTypesElementPark($repoTypes->findOneBy(['idCategorie' => $json->idCategory]));
  218.                 }
  219.                 if (isset($json->idParc)) {
  220.                     $element->setIdParent($repoElement->find($json->idParc));
  221.                 }
  222.                 $errors $validator->validate($element);
  223.                 if (count($errors) > 0) {
  224.                     return $this->json($errors400);
  225.                 }
  226.                 $manager->persist($element);
  227.                 $manager->flush();
  228.             } else {
  229.                 return $this->json([
  230.                     'status' => 400,
  231.                     'message' => "vous ne pouvez pas modifier le client d'un élément"
  232.                 ], 400);
  233.             }
  234.         } catch (\throwable $e) {
  235.             return $this->json([
  236.                 'status' => 400,
  237.                 'message' => $e->getMessage()
  238.             ], 400);
  239.         }
  240.         return $this->json($element201, [], ['groups' => 'affichageElement']);
  241.     }
  242.     /**
  243.      * @IsGranted("ROLE_TECH")
  244.      */
  245.     public function delete($idElementElementsParkRepository $repoElementAccessDecisionManagerInterface $accessDecisionManagerEntityManagerInterface $manager): Response
  246.     {
  247.         //permets de effacer un élément du park d'un client, seul les roles TECH et supperieur peuvent acceder a cette url
  248.         $securizer = new Securizer($accessDecisionManager);
  249.         if ($securizer->isGranted($this->getUser(), "ROLE_TECH")) {
  250.             $element $repoElement->find($idElement);
  251.             $element->setArchive(true);
  252.             $today = new DateTime();
  253.             $element->setDateArchive($today);
  254.             $manager->persist($element);
  255.             $manager->flush();
  256.         } else {
  257.             return $this->json([
  258.                 'status' => 400,
  259.                 'message' => "Vous ne pouvez pas consulter cet élément"
  260.             ], 400);
  261.         }
  262.         return $this->json(true200, [], ['groups' => 'affichageElement']);
  263.     }
  264.     /**
  265.      * @IsGranted("ROLE_TECH")
  266.      */
  267.     public function getTypes(TypesElementParkRepository $repoTypes): Response
  268.     {
  269.         //liste de les types d'elements existants
  270.         $elements $repoTypes->findElementsParc();
  271.         return $this->json($elements200, [], ['groups' => 'affichageElement']);
  272.     }
  273.     /**
  274.      * @IsGranted("ROLE_TECH")
  275.      */
  276.     public function getOrdinateurTypes(CategoriesElementRepository $repoCategoryTypesElementParkRepository $repoTypes): Response
  277.     {
  278.         //liste de les types des elements d'ordinateurs existants
  279.         $category $repoCategory->findOneBy(["categorie" => "supp.ordinateur"]);
  280.         $elements $repoTypes->findBy(["idCategorie" => $category->getId()]);
  281.         return $this->json($elements200, [], ['groups' => 'affichageElement']);
  282.     }
  283.     /**
  284.      * @IsGranted("ROLE_TECH")
  285.      */
  286.     public function searchElements(Request $requestElementsParkRepository $repoParcCategoriesElementRepository $repoCategories): Response
  287.     {
  288.         $jsonRecu json_decode($request->getContent());
  289.         $elements $repoParc->searchElements($jsonRecu->clientId$jsonRecu->search);
  290.         $exclude $repoCategories->findOneBy(['categorie' => 'supp.ordinateur']);
  291.         $res = [];
  292.         for ($i 0$i count($elements); $i++) {
  293.             if ($elements[$i]->getIdTypesElementPark()->getIdCategorie()->getId() != $exclude->getId())
  294.                 $res[] = $elements[$i];
  295.         }
  296.         return $this->json($res200, [], ['groups' => 'affichageElement']);
  297.     }
  298.     /**
  299.      * @IsGranted("ROLE_CLIENT")
  300.      */
  301.     public function getOrdinateurSupp(int $idint $idTypeElementsParkRepository $repoElementsAccessDecisionManagerInterface $accessDecisionManager): Response
  302.     {
  303.         //retourne les elements supplementaires à ordinateurs
  304.         $securizer = new Securizer($accessDecisionManager);
  305.         $elements $repoElements->findOrdinateurSupp($id$idType$securizer$this->getUser());
  306.         return $this->json($elements200, [], ['groups' => 'affichageElement']);
  307.     }
  308. }