<?php
namespace App\Security\Voter;
use App\Entity\Homework;
use App\Entity\HomeworkResult;
use App\Entity\User;
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;
use App\DBAL\Types\HomeworkResultStatusEnum;
use App\DBAL\Types\HomeworkVisionType;
use Symfony\Component\Security\Core\Security;
use App\DBAL\Types\RoleEnumType;
class HomeworkVoter extends Voter
{
const VIEW_ANALYSIS = 'view_analysis';
const SHOW_THE_MORE_BUTTON = 'SHOW_THE_MORE_BUTTON';
private $em;
private $security;
public function __construct(EntityManagerInterface $entityManager, Security $security)
{
$this->em = $entityManager;
$this->security = $security;
}
protected function supports($attribute, $subject)
{
return in_array($attribute, [self::VIEW_ANALYSIS, self::SHOW_THE_MORE_BUTTON])
&& $subject instanceof Homework;
}
/**
* @var string $attribute
* @var Homework $subject
* @see \Symfony\Component\Security\Core\Authorization\Voter\Voter::voteOnAttribute()
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/** @var User $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
$homeworkResultsRepo = $this->em->getRepository(HomeworkResult::class);
switch ($attribute) {
case self::VIEW_ANALYSIS:
$homeworkResult = $homeworkResultsRepo->findBy([
'homework' => $subject->getId(),
'student' => $user->getId(),
'status' => HomeworkResultStatusEnum::STATUS_DONE
]);
return (bool) $homeworkResult;
break;
case self::SHOW_THE_MORE_BUTTON:
if($this->security->isGranted(RoleEnumType::ROLE_ADMIN)){
return true;
}
if($this->security->isGranted(RoleEnumType::ROLE_STUDENT) && $this->security->isGranted('view_analysis', $subject)){
return ($subject->getVision() == HomeworkVisionType::COMPLETED_STUDENTS);
}
break;
}
return false;
}
}