<?php
namespace App\Security\Voter;
use App\Entity\Folder;
use App\Entity\Group;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class FolderVoter extends Voter
{
// these strings are just invented: you can use anything
const CREATE = 'create';
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
private $em;
private $userRepository;
/**
* FolderVoter constructor.
* @param EntityManagerInterface $entityManager
* @param UserRepository $userRepository
*/
public function __construct(EntityManagerInterface $entityManager,UserRepository $userRepository){
$this->em = $entityManager;
$this->userRepository = $userRepository;
}
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::CREATE,self::VIEW,self::EDIT,self::DELETE])
&& $subject instanceof Folder;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/** @var User $user */
$user = $this->userRepository->findOneBy(['email' => $user->getUsername()]);
/** @var Folder $folder*/
$folder = $subject;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::VIEW:
// logic to determine if the user can VIEW
return $this->canView($folder,$user);
break;
}
return false;
}
private function canView(Folder $folder, User $user)
{
/** @var Group $groupUser*/
foreach ($user->getGroups() as $groupUser){
foreach ($folder->getGroups() as $groupFolder){
if($groupUser->getId() === $groupFolder->getId()){
return true;
}
}
}
return false;
}
}