<?php
namespace App\Security\Voter;
use App\Entity\Collective;
use App\Entity\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class CollectiveVoter extends Voter
{
public const LIST = 'collective-list';
public const SHOW = 'collective-show';
public const CREATE = 'collective-create';
public const EDIT = 'collective-edit';
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::LIST, self::SHOW, self::CREATE, self::EDIT])) {
return false;
}
if (!$subject instanceof Collective && $subject) {
return false;
}
return true;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::LIST:
return $this->canList($user);
case self::SHOW:
return $this->canShow($user, $subject);
case self::CREATE:
return $this->canCreate($user);
case self::EDIT:
return $this->canEdit($user);
}
throw new LogicException('This code should not be reached!');
}
/**
* @param User $user
* @return bool
*/
private function canList(User $user): bool
{
if (
$user->hasRole('ROLE_ATCLIENTE') ||
$user->hasRole('ROLE_ATCLIENTE_ADMIN') ||
$user->hasRole('ROLE_ANALYST')
) {
return true;
}
return false;
}
/**
* @param User $user
* @param Collective $collective
* @return bool
*/
private function canShow(User $user, Collective $collective): bool
{
// If there isn't any Collective translation or contract
$collectiveTranslations = $collective->getCollectiveTranslations()->toArray();
if (empty($collectiveTranslations) || empty($collective->getContracts())) {
return false;
}
// If there isn't any ContractLine translation
foreach (($collectiveTranslations[0])->getCollective()->getCollectiveLines() as $contractLine) {
// TODO
// if (!sizeof($contractLine->getTranslations())) {
// return false;
// }
}
// Roles
if (
!$user->hasRole('ROLE_ATCLIENTE') &&
!$user->hasRole('ROLE_ATCLIENTE_ADMIN') &&
!$user->hasRole('ROLE_ANALYST')
) {
return false;
}
return true;
}
/**
* @param User $user
* @return bool
*/
private function canCreate(User $user): bool
{
if ($this->canEdit($user)) {
return true;
}
return false;
}
/**
* @param User $user
* @return bool
*/
private function canEdit(User $user): bool
{
if ($user->hasRole('ROLE_ATCLIENTE_ADMIN')) {
return true;
}
return false;
}
}