src/Controller/Front/ClientController.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use JsonException;
  4. use Exception;
  5. use Throwable;
  6. use App\Controller\PageController;
  7. use App\Dto\Input\RegisterDTO;
  8. use App\Exception\EmailAlreadyExistsException;
  9. use App\Exception\ExpiredCodeException;
  10. use App\Exception\InvalidFieldException;
  11. use App\Form\ClientType;
  12. use App\Form\VehicleType;
  13. use App\Model\Appointment;
  14. use App\Model\Client;
  15. use App\Model\Vehicle;
  16. use App\Repository\MenuRepository;
  17. use App\Service\AppointmentService;
  18. use App\Service\ClientService;
  19. use App\Service\ValidatorService;
  20. use App\Service\VehicleService;
  21. use Doctrine\Persistence\ManagerRegistry;
  22. use Psr\Log\LoggerInterface;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  30. use Symfony\Component\Validator\Validation;
  31. use Symfony\Component\Validator\Validator\ValidatorInterface;
  32. /**
  33.  * @Route("/client", priority="1", options={"expose"=true})
  34.  *
  35.  * @IsGranted("ROLE_CLIENT")
  36.  */
  37. class ClientController extends PageController
  38. {
  39.     use SecurityTokenTrait;
  40.     use RequestRefererTrait;
  41.     private LoggerInterface $logger;
  42.     private ValidatorService $validator;
  43.     private ClientService $clientService;
  44.     private TokenStorageInterface $tokenStorage;
  45.     public function __construct(
  46.         ManagerRegistry $doctrine,
  47.         MenuRepository $menuRepository,
  48.         LoggerInterface $logger,
  49.         ValidatorService $validator,
  50.         ClientService $clientService,
  51.         TokenStorageInterface $tokenStorage
  52.     ) {
  53.         parent::__construct($doctrine$menuRepository);
  54.         $this->logger $logger;
  55.         $this->validator $validator;
  56.         $this->clientService $clientService;
  57.         $this->tokenStorage $tokenStorage;
  58.     }
  59.     /**
  60.      * @Route("/account/{type}", name="client_account")
  61.      *
  62.      * @param VehicleService $vehicleService
  63.      *
  64.      * @throws JsonException
  65.      */
  66.     public function account(string $typeRequest $request): Response
  67.     {
  68.         $this->getPageByType($type);
  69.         $this->_initDatas($request);
  70.         /** @var Client $client */
  71.         $client $this->getUser();
  72.         if (!$client->isInformationConfirmed()) {
  73.             $this->setReferer($request);
  74.             return $this->redirectToRoute('registration_profil');
  75.         }
  76.         $responseData = ['type' => $type];
  77.         // profil
  78.         $profil $this->profil($client$request);
  79.         // vehicle
  80.         $vehicle $this->vehicle($request);
  81.         // history
  82.         $history $this->history($request);
  83.         // appointment
  84.         $appointment $this->appointment($request);
  85.         $responseData array_merge($profil$responseData);
  86.         $responseData array_merge($responseData$vehicle);
  87.         $responseData array_merge($responseData$history);
  88.         $responseData array_merge($responseData$appointment);
  89.         return $this->render('front/client/account.html.twig'$this->getDatas($responseData));
  90.     }
  91.     /**
  92.      * @throws Exception
  93.      */
  94.     protected function profil(Client $clientRequest $request): array
  95.     {
  96.         $form $this->createForm(ClientType::class, $client);
  97.         $form->handleRequest($request);
  98.         return [
  99.             'clientForm' => $form->createView(),
  100.             'client' => $client,
  101.         ];
  102.     }
  103.     /**
  104.      * @Route("/profil/validate", name="client_validate_profil", methods={"POST"})
  105.      *
  106.      * @throws JsonException
  107.      */
  108.     public function validateProfil(Request $requestClientService $clientService): Response
  109.     {
  110.         /** @var Client $client */
  111.         $client $this->getUser();
  112.         $form $this->createForm(ClientType::class, $client);
  113.         $form->handleRequest($request);
  114.         if ($form->isSubmitted()) {
  115.             if($form->isValid()) {
  116.                 // ** @var Client $user */
  117.                 $user $this->getUser();
  118.                 $client->setToken($user->getToken());
  119.                 try {
  120.                     $datas $request->request->get('client')['login'];
  121.                     $datas['code'] = $request->request->get('code');
  122.                     $clientService->updateProfil($client);
  123.                     $needReconnect $clientService->updateLogin($datas);
  124.                     if ($needReconnect) {
  125.                         return $this->json(['reconnect_url' => $this->generateUrl('client_auth')]);
  126.                     }
  127.                     $clientService->updateUser($client);
  128.                 } catch (Throwable $exception) {
  129.                     $this->logger->error($exception->getMessage());
  130.                     if ($exception instanceof ExpiredCodeException) {
  131.                         return $this->json(['code' => $exception->getMessage()], Response::HTTP_BAD_REQUEST);
  132.                     }
  133.                     return $this->json(['error' => true], Response::HTTP_INTERNAL_SERVER_ERROR);
  134.                 }
  135.             } else {
  136.                 $errors $this->validator->getErrors($form);
  137.                 $this->logger->error(json_encode($errorsJSON_THROW_ON_ERROR));
  138.                 return $this->json([
  139.                     'error' => $errors,
  140.                 ], Response::HTTP_BAD_REQUEST);
  141.             }
  142.         }
  143.         return $this->render('front/client/profil.html.twig'$this->getDatas([
  144.             'clientForm' => $form->createView(),
  145.             'client' => $client,
  146.         ]));
  147.     }
  148.     /**
  149.      * @Route("/profil/email/update", name="client_email_update")
  150.      *
  151.      * @return JsonResponse|Response
  152.      *
  153.      * @throws Exception
  154.      */
  155.     public function sendCodeEmail(Request $requestClientService $clientServiceValidatorInterface $validator): Response
  156.     {
  157.         $datas = [];
  158.         try {
  159.             $datas['email'] = $request->request->get('email');
  160.             $resend 'true' == $request->request->get('resend');
  161.             $clientService->sendCodeEmail($datas['email'], $resend);
  162.         } catch (EmailAlreadyExistsException|InvalidFieldException $exception) {
  163.             return $this->json([
  164.                 'email' => true,
  165.                 'message' => $exception->getMessage(),
  166.             ], Response::HTTP_BAD_REQUEST);
  167.         } catch (Throwable $e) {
  168.             return $this->json([
  169.                 'error' => true,
  170.                 'message' => $e->getMessage(),
  171.             ], Response::HTTP_INTERNAL_SERVER_ERROR);
  172.         }
  173.         return $this->json(['success' => true]);
  174.     }
  175.     /**
  176.      * @throws Exception
  177.      */
  178.     protected function vehicle(Request $request): array
  179.     {
  180.         $form $this->createForm(VehicleType::class);
  181.         $form->handleRequest($request);
  182.         /** @var Appointment $appointment */
  183.         $appointment $request->getSession()->get('appointment');
  184.         $appointmentVehicleID '';
  185.         if ($appointment && $appointment->getVehicle()) {
  186.             $appointmentVehicleID $appointment->getVehicle()->getId();
  187.         }
  188.         return [
  189.             'vehicleForm' => $form->createView(),
  190.             'vehicleID' => $appointmentVehicleID,
  191.         ];
  192.     }
  193.     /**
  194.      * @Route("/vehicle/upsert/{id}", name="client_vehicle_upsert", methods={"PUT", "POST"}, defaults={"id": null})
  195.      *
  196.      * @ParamConverter("vehicle", class="App\Model\Vehicle")
  197.      *
  198.      * @throws JsonException
  199.      */
  200.     public function vehicleValidate(Request $requestClientService $clientServiceAppointmentService $appointmentService, ?Vehicle $vehicle null): JsonResponse
  201.     {
  202.         $form $this->createForm(VehicleType::class, $vehicle);
  203.         $form->handleRequest($request);
  204.         if ($form->isSubmitted() && $form->isValid()) {
  205.             try {
  206.                 $clientService->upsertVehicle($vehicle);
  207.                 $appointmentService->needReinitVehicleStep($request->getSession(), $vehicle->getId());
  208.                 return $this->json([
  209.                     'success' => true,
  210.                     'data' => $vehicle,
  211.                 ]);
  212.             } catch (Throwable $exception) {
  213.                 $this->logger->error($exception->getMessage());
  214.             }
  215.         } else {
  216.             $errors $this->validator->getErrors($form);
  217.             $this->logger->error(json_encode($errorsJSON_THROW_ON_ERROR));
  218.             return $this->json([
  219.                 'error' => $errors,
  220.             ], Response::HTTP_INTERNAL_SERVER_ERROR);
  221.         }
  222.         return $this->json([
  223.             'error' => true,
  224.         ], Response::HTTP_INTERNAL_SERVER_ERROR);
  225.     }
  226.     /**
  227.      * @Route("/vehicles/{id}", name="client_vehicles_delete", methods={"DELETE"})
  228.      *
  229.      * @throws Exception
  230.      */
  231.     public function deleteVehicle(Request $requeststring $idClientService $clientServiceAppointmentService $appointmentService): JsonResponse
  232.     {
  233.         try {
  234.             $clientService->deleteVehicle($id);
  235.             $appointmentService->needReinitVehicleStep($request->getSession(), $id);
  236.         } catch (Throwable $exception) {
  237.             $this->logger->error($exception->getMessage());
  238.             return $this->json([
  239.                 'error' => true,
  240.             ], Response::HTTP_INTERNAL_SERVER_ERROR);
  241.         }
  242.         return $this->json([
  243.             'success' => true,
  244.         ]);
  245.     }
  246.     /**
  247.      * @Route("/vehicles", name="client_vehicles")
  248.      *
  249.      * @param Request $request
  250.      *
  251.      * @throws Exception
  252.      */
  253.     public function getCars(ClientService $clientService): JsonResponse
  254.     {
  255.         /** @var Client $client */
  256.         $client $this->getUser();
  257.         $cars = [];
  258.         try {
  259.             $cars $clientService->formatCars($client->getVehicles());
  260.         } catch (Throwable $exception) {
  261.             $this->logger->error(__METHOD__.' : '.$exception->getMessage());
  262.         }
  263.         return $this->json([
  264.             'cars' => $cars,
  265.         ]);
  266.     }
  267.     protected function appointment(Request $request)
  268.     {
  269.         $appointments $this->clientService->getAppointments();
  270.         return [
  271.             'appointments' => $appointments,
  272.         ];
  273.     }
  274.     private function history(Request $request)
  275.     {
  276.         $appointments $this->clientService->getAppointments(false);
  277.         return [
  278.             'histories' => $appointments,
  279.         ];
  280.     }
  281. }