<?php
namespace App\Voter\Fiche;
use App\Entity\Fiche\FicheBatiment;
use App\Entity\User\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class FicheBatimentVoter extends Voter
{
const ANALYSE = 'fiche_batiment_analyse';
const DELETE = 'fiche_batiment_delete';
/**
* @var Security
*/
private $theSecurity;
/**
* @var Request
*/
private $theRequest;
public function __construct(Security $theSecurity, RequestStack $theRequestStack)
{
$this->theSecurity = $theSecurity;
$this->theRequest = $theRequestStack->getCurrentRequest();
}
protected function supports(string $attribute, $subject)
{
if (!in_array($attribute, [self::ANALYSE, self::DELETE])) {
return false;
}
if (
!$subject instanceof FicheBatiment
) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
/** @var FicheBatiment $theFicheBatiment */
$theFicheBatiment = $subject;
switch ($attribute) {
case self::ANALYSE:
return $this->accessAnalyse($theFicheBatiment);
case self::DELETE:
return $this->accessDelete($theFicheBatiment);
default:
return false;
}
}
private function accessAnalyse(FicheBatiment $theFicheBatiment) : bool
{
return $this->hasRight($theFicheBatiment);
}
private function accessDelete(FicheBatiment $theFicheBatiment) : bool
{
return $this->hasRight($theFicheBatiment);
}
private function hasRight(FicheBatiment $theFicheBatiment) : bool
{
if ($theFicheBatiment->getTheFicheBatimentExemple() != null) {
return true;
} elseif ($this->hasRightAnonymous($theFicheBatiment)) {
return true;
} elseif ($this->hasRightUser($theFicheBatiment)) {
return true;
} else {
return false;
}
}
/**
*
* Accès à toutes les fiches pour les Admin, uniquement pour les Fiche de l'Utilisateur dans le cas contraire.
*
* @param FicheBatiment $theFicheBatiment
* @return bool
*/
private function hasRightUser(FicheBatiment $theFicheBatiment) : bool
{
return $this->theSecurity->isGranted('IS_AUTHENTICATED_REMEMBERED') &&
($this->theSecurity->isGranted('ROLE_ADMIN') ||
$theFicheBatiment->getTheUser() == $this->theSecurity->getUser());
}
/**
*
* Si pas connecté, accès uniquement aux fiches qu'il a stocké en Session.
*
* @param FicheBatiment $theFicheBatiment
* @return bool
*/
private function hasRightAnonymous(FicheBatiment $theFicheBatiment) : bool
{
return $this->theSecurity->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') &&
$this->theRequest->getSession()->has('idFicheBatiments') &&
$this->theRequest->getSession()->get('idFicheBatiments') != null &&
in_array($theFicheBatiment->getId(), $this->theRequest->getSession()->get('idFicheBatiments'));
}
}