<?php
namespace App\Security\Voter;
use App\Entity\BlogComment;
use App\Entity\Classified;
use App\Entity\Event;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ClassifiedVoter extends Voter
{
const EDIT = 'edit';
const DELETE = 'delete';
const RENEW = 'renew';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::EDIT, self::DELETE, self::RENEW])) {
return false;
}
if (!$subject instanceof Classified) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var Classified $classified */
$classified = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::EDIT:
case self::DELETE:
case self::RENEW:
return $this->canEditOrDelete($classified, $user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canEditOrDelete(Classified $classified, User $user, TokenInterface $token)
{
return $classified->getCreatedBy() === $user;
}
}