<?php
namespace App\Security\Voter;
use App\Entity\NotificationReceipt;
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\User\UserInterface;
class NotificationReceiptVoter extends Voter
{
public const READ = 'NOTIFICATION_RECEIPT_READ';
public const VIEW = 'NOTIFICATION_RECEIPT_VIEW';
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [self::READ, self::VIEW])
&& $subject instanceof NotificationReceipt;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
/**
* @var User $user
*/
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::READ:
return $this->isUserTheReceiver($user, $subject);
case self::VIEW:
return $this->isUserTheReceiver($user, $subject)
|| in_array('SUPER_ADMIN', $token->getRoleNames())
;
}
return false;
}
private function isUserTheReceiver(User $user, NotificationReceipt $subject): bool
{
return $user->getId() === $subject->getUser()->getId();
}
}