<?php
namespace App\Security\Voter;
use App\Entity\LibraryDocument;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class LibraryDocumentVoter extends Voter
{
const EDIT = 'edit';
const EVALUATE = 'evaluate';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::EVALUATE, self::EDIT])) {
return false;
}
if (!$subject instanceof LibraryDocument) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var LibraryDocument $document */
$document = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::EDIT:
return $this->canEdit($document, $user, $token);
case self::EVALUATE:
return $this->canEvaluate($document, $user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(LibraryDocument $document, User $user, TokenInterface $token)
{
return $document->getCreatedBy() === $user;
}
private function canEvaluate(LibraryDocument $document, User $user, TokenInterface $token)
{
return ($document->getCreatedBy() != $user) && ($document->getStatus() == LibraryDocument::STATUS_PUBLISHED) ;
}
}