<?php
namespace App\Controller;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Entity\Magasin;
use App\Entity\Utilisateur;
abstract class BaseController extends AbstractController
{
protected Connection $connection;
protected EntityManagerInterface $manager;
protected SessionInterface $session;
protected Request $request;
protected ?Magasin $magasin;
protected ?Utilisateur $utilisateur;
public function __construct(
RequestStack $request,
Connection $connection,
ManagerRegistry $doctrine,
TokenStorageInterface $tokenStorage
) {
$this->connection = $connection;
$this->manager = $doctrine->getManager();
$this->request = $request->getCurrentRequest();
$this->session = $this->request->getSession();
// Initialize user
$token = $tokenStorage->getToken();
$this->utilisateur = $token ? $token->getUser() : null;
// Ensure user is not just a string (anonymous)
if ($this->utilisateur instanceof Utilisateur === false) {
$this->utilisateur = null;
}
if(!$this->session->get('magasin') && $this->utilisateur && $this->utilisateur->getDefaultMagasin())
{
$this->session->set('magasin', $this->utilisateur->getDefaultMagasin()->getId());
}
// Consider lazy-loading the magasin when actually needed
$magasinId = $this->session->get('magasin');
$this->magasin = $magasinId ? $this->manager->getRepository(Magasin::class)->find($magasinId) : null;
}
}