<?php
namespace App\Voter;
use App\Entity\Contenu\Page;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class PageVoter 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 Page) {
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(Page $page, $user)
{
if ($this->security->isGranted(['ROLE_ADMIN'])) {
return true;
}
if (true === $page->getVisible()) {
return true;
}
return false;
}
}