<?php
namespace App\Security\Voter;
use App\Entity\Composition\SongWriter;
use App\Entity\User\User;
use App\Service\CompositionService;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class SongWriterVoter extends Voter
{
private const SONG_WRITER_EDIT = 'SONG_WRITER_EDIT';
/**
* @var CompositionService
*/
private $compositionService;
public function __construct(CompositionService $compositionService)
{
$this->compositionService = $compositionService;
}
protected function supports($attribute, $subject)
{
return in_array($attribute, [self::SONG_WRITER_EDIT], true)
&& $subject instanceof SongWriter;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/** @var User $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
// If user can edit a composition, it can also edit a songwriter
case self::SONG_WRITER_EDIT:
return $this->compositionService->userCanEditComposition($user, $subject->getComposition());
}
return false;
}
}