<?php
namespace App\Security\Authorization\Voter;
use App\Entity\BuyersGroup;
use App\Entity\User;
use App\Entity\Vehicle;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ViewVehicleVoter extends Voter
{
public const VIEW = 'view';
public function __construct(private readonly AccessDecisionManagerInterface $decisionManager)
{
}
protected function supports($attribute, $vehicle)
{
if (self::VIEW !== $attribute) {
return false;
}
if (!$vehicle instanceof Vehicle) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $vehicle, TokenInterface $token)
{
$sale = $vehicle->getSale();
$user = $token->getUser();
if (in_array(BuyersGroup::PUBLIC_GROUP, $sale->getBuyersGroups()->toArray())) {
return true;
}
if ($this->decisionManager->decide($token, ['ROLE_ACCESS'])) {
return true;
}
if ($user instanceof User) {
return [] !== array_intersect($user->getBuyersGroups()->toArray(), $sale->getBuyersGroups()->toArray());
}
if ('anon.' === $user) {
return true;
}
return false;
}
}