<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\Material;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MaterialVoter extends Voter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const ARCHIVE = 'archive';
public const DELETE = 'delete';
public const INDIVIDUAL_PARAMETERS = 'individual-parameters';
public const UPLOAD_FILES = 'upload-files';
public const SHOW_FILES = 'show-files';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
$supports = true;
if (!\in_array($attribute, [
self::VIEW,
self::EDIT,
self::ARCHIVE,
self::DELETE,
self::INDIVIDUAL_PARAMETERS,
self::UPLOAD_FILES,
self::SHOW_FILES
], true)) {
$supports = false;
}
if (!$subject instanceof Material) {
$supports = false;
}
return $supports;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
$hasVotePassed = false;
if (!$user instanceof User) {
return $hasVotePassed;
}
/** @var Material $material */
$material = $subject;
switch ($attribute) {
case self::VIEW:
$hasVotePassed = true;
break;
case self::EDIT:
$hasVotePassed = $this->canEdit($material, $user);
break;
case self::ARCHIVE:
$hasVotePassed = $this->canArchive($material, $user);
break;
case self::DELETE:
$hasVotePassed = $this->canDelete($user);
break;
case self::INDIVIDUAL_PARAMETERS:
$hasVotePassed = $this->canIndividualParameters($material, $user);
break;
case self::UPLOAD_FILES:
$hasVotePassed = $this->canUploadFiles($material);
break;
case self::SHOW_FILES:
$hasVotePassed = $this->canShowFiles();
break;
}
return $hasVotePassed;
}
/**
* @param Material $material
* @param User $user
*
* @return bool
*/
private function canEdit(Material $material, User $user): bool
{
return $user->isSystemUser() && $material->isActive();
}
/**
* @param Material $material
* @param User $user
*
* @return bool
*/
private function canArchive(Material $material, User $user): bool
{
return $user->isSystemUser() && $material->isActive();
}
/**
* @param User $user
*
* @return bool
*/
private function canDelete(User $user): bool
{
return $user->isSystemUser();
}
/**
* @param Material $material
* @param User $user
*
* @return bool
*/
private function canIndividualParameters(Material $material, User $user): bool
{
return (!$user->isSystemUser()) && $material->isActive();
}
/**
* @param Material $material
*
* @return bool
*/
private function canUploadFiles(Material $material): bool
{
return $material->isActive();
}
/**
* @return bool
*/
private function canShowFiles(): bool
{
return true;
}
}