<?php
namespace App\Security\Voters;
use App\Entity\Upload;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class UploadsVoter extends Voter
{
private Security $security;
public const CAN_UPLOAD = 'upload.can.be.uploaded';
public const CAN_DOWNLOAD = 'upload.can.be.downloaded';
public const CAN_EDIT = 'upload.can.be.edited';
public const CAN_PUBLIC = 'upload.can.be.public';
private const ATTRIBUTES = [
self::CAN_UPLOAD,
self::CAN_DOWNLOAD,
self::CAN_EDIT,
self::CAN_PUBLIC,
];
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
return in_array($attribute, self::ATTRIBUTES);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
switch ($attribute) {
case self::CAN_UPLOAD:
case self::CAN_DOWNLOAD:
case self::CAN_EDIT:
return $this->hasAccess($subject);
case self::CAN_PUBLIC:
return $this->canPublic($subject);
}
throw new \LogicException('Invalid attribute: ' . $attribute);
}
private function hasAccess(Upload $upload): bool
{
if ($upload->getIsDeleted()) {
return false;
}
if ( in_array('ANON_USER', $upload->getAccessControl()) ) {
return true;
}
if ( in_array('MF_PROFILE', $upload->getAccessControl()) && $this->security->isGranted('user.is_manufacturer')) {
return true;
}
if ($this->security->getUser() && array_intersect($this->security->getUser()->getRoles(), $upload->getAccessControl())) {
return true;
}
return false;
}
private function canPublic(Upload $upload): bool
{
if ($upload->getIsDeleted()) {
return false;
}
if ( in_array('ANON_USER', $upload->getAccessControl()) ) {
return true;
}
return false;
}
}