src/Security/BackOffice/UserAccountSwitchCompanyVoter.php line 27

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  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\BackOffice;
  11. use App\Entity\ManagedOrganization;
  12. use App\Entity\User;
  13. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  14. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  15. /**
  16.  * It grants or denies permissions for actions related to blog posts (such as
  17.  * showing, editing and deleting posts).
  18.  *
  19.  * See https://symfony.com/doc/current/security/voters.html
  20.  *
  21.  * @author Yonel Ceruto <yonelceruto@gmail.com>
  22.  */
  23. class UserAccountSwitchCompanyVoter extends Voter
  24. {
  25.     // Defining these constants is overkill for this simple application, but for real
  26.     // applications, it's a recommended practice to avoid relying on "magic strings"
  27.     const SHOW 'show';
  28.     const EDIT 'edit';
  29.     const DELETE 'delete';
  30.     /**
  31.      * {@inheritdoc}
  32.      */
  33.     protected function supports($attribute$subject): bool
  34.     {
  35.         // this voter is only executed for three specific permissions on Post objects
  36.         return $subject instanceof ManagedOrganization && $attribute == 'switch_company';
  37.     }
  38.     /**
  39.      * {@inheritdoc}
  40.      */
  41.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  42.     {
  43.         $user $token->getUser();
  44.         // the user must be logged in; if not, deny permission
  45.         if (!$user instanceof User) {
  46.             return false;
  47.         }
  48.         // the logic of this voter is pretty simple: if the logged user is the
  49.         // author of the given blog post, grant permission; otherwise, deny it.
  50.         // (the supports() method guarantees that $post is a Post object)
  51.         return $user === $subject->getManager();
  52.     }
  53. }