<?php
namespace App\Controller;
use App\Entity\Utilisateur;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Class BaseController.
*/
class BaseController extends AbstractController
{
public const BAG_TOAST = 'toast';
protected EntityManagerInterface $entityManager;
protected TranslatorInterface $translator;
private bool $isInit = false;
#[Required]
public function setEntityManager(EntityManagerInterface $entityManager): void
{
$this->entityManager = $entityManager;
}
#[Required]
public function setTranslator(TranslatorInterface $translator): void
{
$this->translator = $translator;
}
public function getUser(): Utilisateur
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = parent::getUser();
if (!$user instanceof Utilisateur) {
throw $this->createAccessDeniedException('Vous n\'êtes pas connecté');
}
return $user;
}
public function getEntityManager(): EntityManagerInterface
{
return $this->entityManager;
}
protected function toast(string $type, $text, $title = null): void
{
$this->addFlash(self::BAG_TOAST, [
'type' => $type,
'text' => $text instanceof TranslatableMessage ? $text->trans($this->translator) : $text,
'title' => $title instanceof TranslatableMessage ? $title->trans($this->translator) : $title,
]);
}
protected function checkAccessApi(Request $request): void
{
if (!$request->headers->has('x-api-key')) {
throw $this->createAccessDeniedException('Accès non autorisé');
}
if ($request->headers->get('x-api-key') !== $this->getParameter('api_key')) {
throw $this->createAccessDeniedException('Accès non autorisé');
}
}
}