<?php
namespace App\Security\SuperheroFreight;
use App\Entity\CommonData\User;
use App\Entity\SuperheroFreight\ReplenishmentOrder;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Class ReplenishmentOrderVoter
*
* @package App\Security\SuperheroFreight
*/
class ReplenishmentOrderVoter extends Voter
{
/**
* @var string
*/
const VIEW = 'view';
/**
* @var string
*/
const EDIT = 'edit';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
if (!$subject instanceof ReplenishmentOrder) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var ReplenishmentOrder $replenishmentOrder */
$replenishmentOrder = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($replenishmentOrder, $user);
case self::EDIT:
return $this->canEdit($replenishmentOrder, $user);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param ReplenishmentOrder $replenishmentOrder
* @param User $user
*
* @return bool
*/
private function canView(ReplenishmentOrder $replenishmentOrder, User $user): bool
{
return $user === $replenishmentOrder->getShfUser()->getUser() && !$replenishmentOrder->isDeleted();
}
/**
* @param ReplenishmentOrder $replenishmentOrder
* @param User $user
*
* @return bool
*/
private function canEdit(ReplenishmentOrder $replenishmentOrder, User $user): bool
{
return $replenishmentOrder->isEditable() &&
$user === $replenishmentOrder->getShfUser()->getUser() &&
!$replenishmentOrder->isDeleted();
}
}