<?php
namespace App\Controller;
use App\Service\Securizer;
use App\Entity\ElementsPark;
use App\Entity\TypesElementPark;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\ElementsParkRepository;
use Symfony\Component\HttpFoundation\Request;
use App\Repository\TypesElementParkRepository;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\CategoriesElementRepository;
use DateTime;
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;
use Symfony\Component\Validator\Constraints\Date;
class ElementsParkController extends AbstractController
{
/**
* @IsGranted("ROLE_TECH")
*/
public function index(int $idClient, ElementsParkRepository $repoElement): Response
{
//liste tous les elements de parc qu'il est possible d'afficher
$elements = $repoElement->findElementsPark($idClient);
return $this->json($elements, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function voir($idClient, $idElement, ElementsParkRepository $repoElement): Response
{
$elements = $repoElement->findElementsPark($idClient);
for ($i = 0; $i < count($elements); $i++) {
if ($elements[$i]['id'] == (int)$idElement) $element = $elements[$i];
}
if (isset($element))
return $this->json($element, 200, [], ['groups' => 'affichageElement']);
else
return $this->json([
'status' => 400,
'message' => 'L’objet n’appartient pas au parc sélectionné'
], 400);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function getArchive(int $idClient, ElementsParkRepository $repoElement): Response
{
//liste tous les elements de parc qu'il est possible d'afficher
$elements = $repoElement->findElementsPark($idClient, true);
return $this->json($elements, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function creer(Request $request, ValidatorInterface $validator, SerializerInterface $serializer, EntityManagerInterface $manager): Response
{
// Creer un nouvel élément de park, seul les roles tech et admin peuvent accer a cette url
$jsonRecu = $request->getContent();
try {
//transforme le json reçu en entity
$element = $serializer->deserialize($jsonRecu, ElementsPark::class, 'json');
//validation des données reçus
$errors = $validator->validate($element);
if (count($errors) > 0) {
return $this->json($errors, 400);
}
$manager->persist($element);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($element, 201, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function uploadFile(Request $request, EntityManagerInterface $manager, ElementsParkRepository $repoElement, AccessDecisionManagerInterface $accessDecisionManager): Response
{
// charger un fichier a un élément de park, seul les roles tech ou supperieur peuvent accer a cette url
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
try {
$file = $request->files->get('myFile');
// ** Vérifier si les dossiers existes et si oui supprimer le contenu
$path = dirname(__DIR__) . '/../documents/parc/client_' . $_POST["clientId"] . "/";
if (!is_dir($path))
mkdir($path, 0777, true);
// ** Télécharger le fichier
if (!empty($file)) {
$file->move(
$path,
$_FILES["myFile"]["name"]
);
}
$entity = $repoElement->find($_POST["elementId"]);
$update = $entity->getData();
if (!isset($update["files"]))
$update["files"] = [];
array_push($update["files"], $_FILES["myFile"]["name"]);
$entity->setData($update);
$manager->persist($entity);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($entity, 201, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function getFile($data, AccessDecisionManagerInterface $accessDecisionManager)
{
// télécharger un fichier d'un élément de parc, seul les roles tech ou supperieur peuvent accer a cette url
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
try {
$path = dirname(__DIR__) . "/../documents/parc/client_" . str_replace("::filename", "/", str_replace("::extension", ".", $data));
if (!is_file($path))
return $this->json([
'status' => 400,
'message' => "Aucun fichier de ce type n’a été trouvé"
], 400);
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
// header('Access-Control-Allow-Origin: ' . "http://localhost:8001");
header('Access-Control-Allow-Origin: ' . "https://extranet.cco-info.fr/");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
flush(); // Flush system output buffer
echo readfile($path);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function deleteFile($data, int $id, ElementsParkRepository $repoElement, EntityManagerInterface $manager, AccessDecisionManagerInterface $accessDecisionManager): Response
{
// permets de effacer un fichier d'un element de parc
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
try {
$entity = $repoElement->find($id);
$fileName = str_replace("::extension", ".", explode("::filename", $data)[1]);
$path = dirname(__DIR__) . "/../documents/parc/client_" . $entity->getIdClient()->getId() . "/" . str_replace("::filename", "/", str_replace("::extension", ".", $data));
if (!is_file($path))
return $this->json([
'status' => 400,
'message' => "Aucun fichier de ce type n’a été trouvé"
], 400);
unlink($path);
$update = $entity->getData();
array_splice($update["files"], array_search($fileName, $update["files"]), 1);
$entity->setData($update);
$manager->persist($entity);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json(true, 201);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function modif($idElement, Request $request, ElementsParkRepository $repoElement, TypesElementParkRepository $repoTypes, SerializerInterface $serializer, ValidatorInterface $validator, EntityManagerInterface $manager): Response
{
//modifi un élément existant, seul les roles tech et plus peuvent acceder a cette url
$element = $repoElement->find($idElement);
$idClientDepart = $element->getIdClient()->getId();
if ($element == null) {
return $this->json([
'status' => 400,
'message' => "l'élément à modifier n'existe pas"
], 400);
}
try {
if ($element->getIdClient()->getId() == $idClientDepart) {
$json = $request->getContent();
$serializer->deserialize($json, ElementsPark::class, 'json', ['object_to_populate' => $element]);
$json = json_decode($json);
if (isset($json->idCategory)) {
$element->setIdTypesElementPark($repoTypes->findOneBy(['idCategorie' => $json->idCategory]));
}
if (isset($json->idParc)) {
$element->setIdParent($repoElement->find($json->idParc));
}
$errors = $validator->validate($element);
if (count($errors) > 0) {
return $this->json($errors, 400);
}
$manager->persist($element);
$manager->flush();
} else {
return $this->json([
'status' => 400,
'message' => "vous ne pouvez pas modifier le client d'un élément"
], 400);
}
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($element, 201, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function delete($idElement, ElementsParkRepository $repoElement, AccessDecisionManagerInterface $accessDecisionManager, EntityManagerInterface $manager): Response
{
//permets de effacer un élément du park d'un client, seul les roles TECH et supperieur peuvent acceder a cette url
$securizer = new Securizer($accessDecisionManager);
if ($securizer->isGranted($this->getUser(), "ROLE_TECH")) {
$element = $repoElement->find($idElement);
$element->setArchive(true);
$today = new DateTime();
$element->setDateArchive($today);
$manager->persist($element);
$manager->flush();
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
}
return $this->json(true, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function getTypes(TypesElementParkRepository $repoTypes): Response
{
//liste de les types d'elements existants
$elements = $repoTypes->findElementsParc();
return $this->json($elements, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function getOrdinateurTypes(CategoriesElementRepository $repoCategory, TypesElementParkRepository $repoTypes): Response
{
//liste de les types des elements d'ordinateurs existants
$category = $repoCategory->findOneBy(["categorie" => "supp.ordinateur"]);
$elements = $repoTypes->findBy(["idCategorie" => $category->getId()]);
return $this->json($elements, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function searchElements(Request $request, ElementsParkRepository $repoParc, CategoriesElementRepository $repoCategories): Response
{
$jsonRecu = json_decode($request->getContent());
$elements = $repoParc->searchElements($jsonRecu->clientId, $jsonRecu->search);
$exclude = $repoCategories->findOneBy(['categorie' => 'supp.ordinateur']);
$res = [];
for ($i = 0; $i < count($elements); $i++) {
if ($elements[$i]->getIdTypesElementPark()->getIdCategorie()->getId() != $exclude->getId())
$res[] = $elements[$i];
}
return $this->json($res, 200, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function getOrdinateurSupp(int $id, int $idType, ElementsParkRepository $repoElements, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//retourne les elements supplementaires à ordinateurs
$securizer = new Securizer($accessDecisionManager);
$elements = $repoElements->findOrdinateurSupp($id, $idType, $securizer, $this->getUser());
return $this->json($elements, 200, [], ['groups' => 'affichageElement']);
}
}