<?php
/**
* Copyright (C) SUEZ Smart Solutions - All Rights Reserved
* On’Connect Gateway Management, 2018
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* For the full copyright and license information, please report to the LICENSE CONTRACT.
*/
namespace TSMS\AdminBundle\Security\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use TSMS\CoreBundle\Entity\Contract;
use TSMS\CoreBundle\Entity\User;
use TSMS\CoreBundle\Manager\PerimeterManager;
class ContractVoter implements VoterInterface
{
/**
* @var PerimeterManager
*/
private $perimeterManager;
/**
* ContractVoter constructor.
*
* @param PerimeterManager $perimeterManager
*/
public function __construct(PerimeterManager $perimeterManager)
{
$this->perimeterManager = $perimeterManager;
}
const VIEW = 'view';
/**
* @param string $attribute
*
* @return bool
*/
public function supportsAttribute($attribute)
{
return self::VIEW === $attribute;
}
/**
* @param string $class
*
* @return bool
*/
public function supportsClass($class)
{
$supportedClass = 'TSMS\CoreBundle\Entity\Contract';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
/**
* @param TokenInterface $token
* @param Contract $contract
* @param array $attributes
*/
public function vote(TokenInterface $token, $contract, array $attributes)
{
if (
!is_object($contract) ||
(null !== $contract && !$this->supportsClass(get_class($contract)))
) {
return VoterInterface::ACCESS_ABSTAIN;
}
if (1 !== count($attributes)) {
throw new \InvalidArgumentException(
'Only one attribute is allowed for VIEW'
);
}
$attribute = $attributes[0];
if (!$this->supportsAttribute($attribute)) {
return VoterInterface::ACCESS_ABSTAIN;
}
/** @var User $user */
$user = $token->getUser();
$administeredContracts = $user->getContracts();
$userPerimeters = $user->getPerimeters();
if ($userPerimeters) {
$perimeterManager = $this->perimeterManager;
$perimeters = [];
foreach ($userPerimeters as $perimeter) {
$perimeters = array_merge($perimeters, $this->perimeterManager->getChildrenPerimeterCodes($perimeter));
$perimeters[] = $perimeter->getPerimeterCode();
}
$administeredContracts = array_filter(
$administeredContracts->toArray(),
function (Contract $contract) use ($perimeters) {
// check if perimeter not found
if (null == $contract->getPerimeter()) {
return false;
}
return in_array($contract->getPerimeter()->getPerimeterCode(), $perimeters);
}
);
}
foreach ($administeredContracts as $administeredContract) {
if ($administeredContract->getId() === $contract->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
}
return VoterInterface::ACCESS_DENIED;
}
}