src/Controller/BaseController.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Utilisateur;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Translation\TranslatableMessage;
  8. use Symfony\Contracts\Service\Attribute\Required;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. /**
  11. * Class BaseController.
  12. */
  13. class BaseController extends AbstractController
  14. {
  15. public const BAG_TOAST = 'toast';
  16. protected EntityManagerInterface $entityManager;
  17. protected TranslatorInterface $translator;
  18. private bool $isInit = false;
  19. #[Required]
  20. public function setEntityManager(EntityManagerInterface $entityManager): void
  21. {
  22. $this->entityManager = $entityManager;
  23. }
  24. #[Required]
  25. public function setTranslator(TranslatorInterface $translator): void
  26. {
  27. $this->translator = $translator;
  28. }
  29. public function getUser(): Utilisateur
  30. {
  31. $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  32. $user = parent::getUser();
  33. if (!$user instanceof Utilisateur) {
  34. throw $this->createAccessDeniedException('Vous n\'êtes pas connecté');
  35. }
  36. return $user;
  37. }
  38. public function getEntityManager(): EntityManagerInterface
  39. {
  40. return $this->entityManager;
  41. }
  42. protected function toast(string $type, $text, $title = null): void
  43. {
  44. $this->addFlash(self::BAG_TOAST, [
  45. 'type' => $type,
  46. 'text' => $text instanceof TranslatableMessage ? $text->trans($this->translator) : $text,
  47. 'title' => $title instanceof TranslatableMessage ? $title->trans($this->translator) : $title,
  48. ]);
  49. }
  50. protected function checkAccessApi(Request $request): void
  51. {
  52. if (!$request->headers->has('x-api-key')) {
  53. throw $this->createAccessDeniedException('Accès non autorisé');
  54. }
  55. if ($request->headers->get('x-api-key') !== $this->getParameter('api_key')) {
  56. throw $this->createAccessDeniedException('Accès non autorisé');
  57. }
  58. }
  59. }