<?php
namespace App\Controller\Admin;
use App\Entity\Client;
use App\Repository\ClientRepository;
use App\Security\NotClientContextException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
abstract class AbstractAdminController extends AbstractController {
protected $clientrepo;
/**
* @var Client
*/
protected $client;
/**
* @var EntityManager
*/
protected $em;
/**
* @var SessionInterface
*/
protected $session;
/**
* @var Environment
*/
protected $twig;
/**
* @var Request
*/
protected $request;
/**
* @var Security
*/
protected $security;
public function __construct(ClientRepository $clientrepo, EntityManagerInterface $em, RequestStack $stack, Environment $twig, Security $security) {
$this->clientrepo = $clientrepo;
$this->em = $em;
$this->session = $stack->getSession();
$this->request = $stack->getMainRequest();
$this->twig = $twig;
$this->security = $security;
// Load client from user or from session for admins
if($security->isGranted("ROLE_ADMIN") && $this->session->has('MANAGE_CLIENT') ) {
$this->loadClient($this->session->get('MANAGE_CLIENT'));
} else if($security->isGranted("ROLE_CLIENT") && $security->getUser()->getClient()) {
$this->loadClient($security->getUser()->getClient()->getId());
} else {
$this->twig->addGlobal("client", null);
}
}
protected function isClientContext() {
return ($this->client != null);
}
protected function getClient() {
if(!$this->client) throw new NotClientContextException();
return $this->client;
}
protected function ensureClient(Client $expectedClient) {
// IF EXPECTED CLIENT IS PROVIDED ENSURE THE GOOD ONE IS LOGGED
if(!$this->client || $expectedClient->getId() != $this->client->getId()) throw new NotClientContextException($expectedClient);
return $this->client;
}
protected function loadClient($clientid) {
$this->client = $this->clientrepo->find($clientid);
if(!$this->client) throw $this->createAccessDeniedException();
$this->twig->addGlobal("client", $this->client);
}
protected function generateUrlWihClient($route, array $parameters = []) {
if(!$this->client) throw new Exception("Method getClient should be called first");
if($this->isGranted("ROLE_ADMIN")) $parameters['client'] = $this->client->getId();
return $this->generateUrl($route, $parameters);
}
}