<?php
namespace App\Security\Voter;
use App\Entity\GalleryPic;
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 GalleryPicVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
const MODERATE = 'moderate';
const VALIDATE = 'validate';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE, self::MODERATE, self::VALIDATE])) {
return false;
}
if (!$subject instanceof GalleryPic) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$currentUser = $token->getUser();
if (!$currentUser instanceof User) {
return false;
}
/** @var GalleryPic $picture */
$picture = $subject;
if ($this->security->isGranted(User::ROLE_GALLERY_ADMIN)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($picture, $currentUser);
case self::EDIT:
case self::DELETE:
return $this->canEditOrDelete($picture, $currentUser);
case self::MODERATE:
return $this->canModerate();
case self::VALIDATE:
return $this->canValidate($picture);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(GalleryPic $picture, User $currentUser): bool
{
return $picture->getUser() === $currentUser ||
GalleryPic::STATUS_PUBLISHED &&
(
!$picture->getFriendsOnly() ||
$picture->getUser()->isFriendWith($currentUser)
);
}
private function canEditOrDelete(GalleryPic $picture, User $currentUser): bool
{
return $picture->getUser() === $currentUser;
}
private function canModerate(): bool
{
return $this->security->isGranted(User::ROLE_GALLERY_ADMIN);
}
private function canValidate(GalleryPic $picture): bool
{
return $this->canModerate() && $picture->getStatus() === GalleryPic::STATUS_MODERATION;
}
}