<?php
namespace App\Security;
use Aqarmap\Bundle\ListingBundle\Entity\Listing;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ListingOwnerVoter extends Voter
{
const OWNER = 'LISTING_OWNER';
private AuthorizationCheckerInterface $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === self::OWNER && $subject instanceof Listing;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var Listing $listing */
$listing = $subject;
return $user->getId() === $listing->getUser()->getId();
}
}