<?php
namespace App\Security\Voter;
use App\Entity\GalleryAlbum;
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 AlbumVoter extends Voter
{
const ADD_PICTURE = 'addPicture';
const EDIT = 'edit';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::EDIT, self::ADD_PICTURE])) {
return false;
}
if (!$subject instanceof GalleryAlbum) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var GalleryAlbum $album */
$album = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::EDIT:
case self::ADD_PICTURE:
return $this->canEdit($album, $user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(GalleryAlbum $album, User $user, TokenInterface $token)
{
return $album->getUser() === $user;
}
}