<?php
namespace App\Controller;
use App\Entity\Project;
use App\Entity\Record;
use App\Entity\UserProject;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class TestController extends AbstractController
{
/**
* @Route("/",name="home")
*
* @throws RuntimeError
* @throws LoaderError
* @throws SyntaxError
*/
public function indexAction(Environment $twig): Response
{
return new Response($twig->render('index.html.twig'));
}
/**
* @Route("/api", name="test")
*/
public function api(): JsonResponse
{
$response = new JsonResponse();
$response->setContent(json_encode([
'userIdentifier' => $this->getUser()->getUserIdentifier(),
'roles' => $this->getUser()->getRoles(),
]));
return $response;
}
/**
* @throws NotFoundHttpException
*
* @Route("/api/projectRoles/{id_project}", name="projectRoles")
*/
public function projectRoles(int $id_project, ManagerRegistry $doctrine): JsonResponse
{
$project = $doctrine->getRepository(Project::class)->find($id_project);
if (!$project) {
throw $this->createNotFoundException('Project not found');
}
$userProject = $doctrine
->getRepository(UserProject::class)
->findOneBy(['user' => $this->getUser(), 'project' => $project]);
return new JsonResponse($userProject->getRole());
}
/**
* @param EntityManager $manager
*
* @throws ORMException
*
* @Route("/purge")
*/
public function purgeAction(EntityManagerInterface $manager): JsonResponse
{
$dateExpiration = new \DateTime('now');
$records = $manager->getRepository(Record::class)
->createQueryBuilder('r')
->where('r.recordTime <= :dateExpiration')
->setParameter('dateExpiration', $dateExpiration)
->getQuery()
->getResult();
$recordCount = count($records);
$out = '';
while ($record = array_shift($records)) {
$manager->remove($record);
$product = $record->getProduct();
$manager->flush();
$leftRecords = $manager->getRepository(Record::class)->findBy(['product' => $product]);
if (0 == count($leftRecords)) {
$manager->remove($product);
$manager->flush();
}
}
return new JsonResponse(['record_count' => $recordCount]);
}
}