src/Security/Voter/Scholar/Front/ModuleVoter.php line 21

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the nellapp package.
  4. *
  5. * (c) Benjamin Georgeault
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace App\Security\Voter\Scholar\Front;
  11. use App\Entity\Scholar\Module\Module;
  12. use App\Entity\Scholar\Training\Training;
  13. use App\Service\Scholar\ScholarNavigationSecurityService;
  14. use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
  15. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  16. use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
  17. class ModuleVoter implements VoterInterface
  18. {
  19. public function __construct(
  20. private ScholarNavigationSecurityService $scholarNavigationSecurityService,
  21. )
  22. {
  23. }
  24. private function isSubjectValid($subject): bool
  25. {
  26. if (!is_array($subject)) {
  27. return false;
  28. }
  29. if (
  30. !array_key_exists('training', $subject)
  31. || !array_key_exists('module', $subject)
  32. || array_key_exists('lesson', $subject)
  33. ) {
  34. return false;
  35. }
  36. $training = $subject['training'];
  37. $module = $subject['module'];
  38. return $training instanceof Training && $module instanceof Module;
  39. }
  40. public function vote(TokenInterface $token, $subject, array $attributes): int
  41. {
  42. $user = $token->getUser();
  43. if (!$user instanceof UserInterface) {
  44. return false;
  45. }
  46. if (!$this->isSubjectValid($subject)) {
  47. return self::ACCESS_ABSTAIN;
  48. }
  49. if (!in_array('FRONT_ACCESS', $attributes)) {
  50. return self::ACCESS_ABSTAIN;
  51. }
  52. return $this->scholarNavigationSecurityService->canAccessModule(
  53. $subject['training'],
  54. $subject['module'],
  55. ) ? self::ACCESS_GRANTED : self::ACCESS_DENIED;
  56. }
  57. }