<?php
namespace App\Security\Voters;
use App\Entity\Manufacturer;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class UserVoter extends Voter
{
private Security $security;
public const IF_USER_AGREED_CONDITIONS = 'user.can_access';
public const IS_APP_CUSTOMER = 'user.is_app_customer';
public const IS_MANUFACTURER = 'user.is_manufacturer';
private const ATTRIBUTES = [
self::IF_USER_AGREED_CONDITIONS,
self::IS_MANUFACTURER,
self::IS_APP_CUSTOMER,
];
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
return in_array($attribute, self::ATTRIBUTES);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
switch ($attribute) {
case self::IF_USER_AGREED_CONDITIONS:
return $this->canAccess($subject);
case self::IS_APP_CUSTOMER:
return $this->isAppCustomer($subject);
case self::IS_MANUFACTURER:
return $this->isManufacturer($subject);
}
throw new \LogicException('Invalid attribute: '.$attribute);
}
private function canAccess($subject) : bool
{
if ( !$this->security->getUser() ) {
return false;
}
if ( $this->security->isGranted('user.is_manufacturer') ) {
return false;
}
return true;
}
private function isAppCustomer(?User $user): bool
{
// return (bool)$this->security->getUser()->getCustomer(); // please use me --- TODO
if (!$user) {
return false;
}
return (bool)$user->getCustomer();
}
private function isManufacturer(): bool
{
if ( !$user = $this->security->getUser()) {
return false;
}
return $user->getManufacturer() instanceof Manufacturer;
}
}