<?php
declare(strict_types=1);
namespace App\Api\Security\Voter;
use App\Api\Entity\User;
use App\Api\Entity\UserAbstract;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class UserActionsVoter extends Voter
{
public const DELETE = 'delete';
public const UPDATE = 'update';
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::DELETE, self::UPDATE])) {
return false;
}
if (!$subject instanceof UserAbstract) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$authenticatedUser = $token->getUser();
if (!$authenticatedUser instanceof UserAbstract) {
return false;
}
/** @var User $post */
$userFromRequest = $subject;
switch ($attribute) {
case self::DELETE:
return $this->canDelete($userFromRequest);
case self::UPDATE:
return $this->canUpdate($userFromRequest, $authenticatedUser);
}
}
private function canDelete(UserInterface $user): bool
{
return $user->isTdc1Manager();
}
private function canUpdate(UserInterface $userFromRequest, UserInterface $authenticatedUser): bool
{
return $userFromRequest->getId() === $authenticatedUser->getId();
}
}