src/Security/Voter/ContractPriceVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\ContractPrice\Contract;
  4. use App\Entity\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class ContractPriceVoter extends Voter
  10. {
  11. const EDIT = 'edit';
  12. const DELETE = 'delete';
  13. public function __construct(
  14. protected Security $security,
  15. protected EntityManagerInterface $entityManager
  16. ) {
  17. }
  18. protected function supports(string $attribute, $subject): bool
  19. {
  20. // if the attribute isn't one we support, return false
  21. if (!in_array($attribute, [self::EDIT, self::DELETE], true)) {
  22. return false;
  23. }
  24. // only vote on `Contract` objects
  25. if (!$subject instanceof Contract) {
  26. return false;
  27. }
  28. return true;
  29. }
  30. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  31. {
  32. $loggedUser = $token->getUser();
  33. if (!$loggedUser instanceof User) {
  34. // the user must be logged in; if not, deny access
  35. return false;
  36. }
  37. switch ($attribute) {
  38. case self::EDIT:
  39. return $this->canEdit($loggedUser);
  40. case self::DELETE:
  41. return $this->canDelete($loggedUser);
  42. }
  43. throw new \LogicException('This code should not be reached!');
  44. }
  45. private function canEdit(User $loggedUser): bool
  46. {
  47. if (!$this->security->isGranted('ROLE_CAN_VIEW_CONTRACTS')) {
  48. return false;
  49. }
  50. if ($this->security->isGranted('ROLE_CAN_EDIT_CONTRACT')) {
  51. return true;
  52. }
  53. return false;
  54. }
  55. private function canDelete(User $loggedUser): bool
  56. {
  57. if (!$this->security->isGranted('ROLE_CAN_VIEW_CONTRACTS')) {
  58. return false;
  59. }
  60. if ($this->security->isGranted('ROLE_CAN_DELETE_CONTRACT')) {
  61. return true;
  62. }
  63. return false;
  64. }
  65. }