<?php
declare(strict_types=1);
namespace App\Security\Blo;
use App\Entity\Blo\Shop;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ShopVoter extends Voter
{
public const VIEW = 'blo_shop_view';
public const EDIT = 'blo_shop_edit';
public const MANAGE = 'blo_shop_manage';
protected function supports(string $attribute, mixed $subject): bool
{
return $subject instanceof Shop
&& \in_array($attribute, [self::VIEW, self::EDIT, self::MANAGE], true);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return $attribute === self::VIEW;
}
/** @var Shop $shop */
$shop = $subject;
return match ($attribute) {
self::VIEW => true,
self::EDIT => $this->canEdit($shop, $user),
self::MANAGE => $this->canManage($shop, $user),
default => false,
};
}
private function canEdit(Shop $shop, User $user): bool
{
if (\in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
return $shop->getOwner() === $user;
}
private function canManage(Shop $shop, User $user): bool
{
return $this->canEdit($shop, $user);
}
}