<?php
declare(strict_types=1);
namespace App\Security;
use App\Entity\Attachment;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AttachmentVoter extends Voter
{
public const EDIT = 'ATTACHMENT_EDIT';
public function supportsAttribute(string $attribute): bool
{
return $attribute === self::EDIT;
}
public function supportsType(string $subjectType): bool
{
return is_a($subjectType, Attachment::class, true);
}
protected function supports(string $attribute, mixed $subject): bool
{
return $subject instanceof Attachment && $this->supportsAttribute($attribute);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
/** @var Attachment $subject */
$user = $token->getUser();
return $user instanceof User && $this->isOwner($subject, $user);
}
private function isOwner(Attachment $attachment, User $user): bool
{
$owner = $attachment->createdBy;
return $owner instanceof User && $owner->getId()->equals($user->getId());
}
}