<?php
/**
* @license SILK SOFTWARE HOUSE SP Z O O
*/
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Class UserVoter.
*/
class UserVoter extends Voter
{
const SHOW = 'show';
const NEW = 'new';
const EDIT = 'edit';
const DELETE = 'delete';
/**
* Supports.
*
* @param string $attribute
* @param object $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::SHOW, self::NEW, self::EDIT, self::DELETE])) {
return false;
}
if (!$subject instanceof User) {
return false;
}
return true;
}
/**
* Vote on attribute.
*
* @param string $attribute
* @param User $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($user->hasRole('ROLE_ADMIN')) {
return true;
}
if (!$user->hasRole('ROLE_CUSTOMER')) {
return false;
}
if (in_array($attribute, [self::SHOW, self::NEW])) {
return $user->hasRole('ROLE_USER');
}
if (!$user->getActiveCustomer() || !$subject->getActiveCustomer()) {
return false;
}
if ($subject->getActivatedAt() && $subject->hasRole('ROLE_CUSTOMER')) {
return false;
}
return $subject->getActiveCustomer()->getId() === $user->getActiveCustomer()->getId();
}
}