src/Security/ApiVersionVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\UserManagement\ApiUser;
  4. use App\Exception\ApiVersionMismatchHigh;
  5. use App\Exception\ApiVersionMismatchLow;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ApiVersionVoter extends Voter {
  9.     public const API_VERSION 'API_VERSION';
  10.     protected function supports($attribute$subject): bool {
  11.         if ($attribute !== self::API_VERSION) {
  12.             return false;
  13.         }
  14.         if (!is_int($subject)) {
  15.             return false;
  16.         }
  17.         return true;
  18.     }
  19.     /**
  20.      * Check if User is available and if the user's clinic has the right API version for this call
  21.      * @param $attribute
  22.      * @param $subject
  23.      * @param TokenInterface $token
  24.      * @return bool
  25.      * @throws ApiVersionMismatchHigh
  26.      * @throws ApiVersionMismatchLow
  27.      */
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool {
  29.         $user $token->getUser();
  30.         if (!$user instanceof ApiUser || === $clinicApiVersion $user->getClinicApiVersion()) {
  31.             return false;
  32.         }
  33.         if ($subject === $clinicApiVersion) {
  34.             return true;
  35.         }
  36.         if ($subject $clinicApiVersion) {
  37.             throw new ApiVersionMismatchLow("API version mismatch - Clinic API version: " $clinicApiVersion);
  38.         }
  39.         if ($subject $clinicApiVersion) {
  40.             throw new ApiVersionMismatchHigh("API version mismatch - Clinic API version: " $clinicApiVersion);
  41.         }
  42.         return false;
  43.     }
  44.     private function canView(Post $postUser $user): bool {
  45.         // if they can edit, they can view
  46.         if ($this->canEdit($post$user)) {
  47.             return true;
  48.         }
  49.         // the Post object could have, for example, a method `isPrivate()`
  50.         return !$post->isPrivate();
  51.     }
  52.     private function canEdit(Post $postUser $user): bool {
  53.         // this assumes that the Post object has a `getOwner()` method
  54.         return $user === $post->getOwner();
  55.     }
  56. }