<?php
namespace App\Voter;
use App\Entity\Boutique\Offre;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class OffreVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW))) {
return false;
}
if (!$subject instanceof Offre) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Offre $offre, $user)
{
if ($this->security->isGranted(['ROLE_ADMIN', 'ROLE_MUTUALISE'])) {
return true;
}
if (true === $offre->getVisible()) {
$dateActuelle = new \DateTime();
if (
$offre->getPublishedAt() <= $dateActuelle &&
($offre->getExpiredAt() >= $dateActuelle || is_null($offre->getExpiredAt()))
) {
return true;
}
}
return false;
}
}