vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/EventListener/UserDeleteListener.php line 33

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Sylius package.
  4. *
  5. * (c) Paweł Jędrzejewski
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\UserBundle\EventListener;
  12. use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
  13. use Sylius\Component\User\Model\UserInterface;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  16. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. use Webmozart\Assert\Assert;
  19. final class UserDeleteListener
  20. {
  21. public function __construct(private TokenStorageInterface $tokenStorage, private SessionInterface $session)
  22. {
  23. }
  24. /**
  25. * @throws \InvalidArgumentException
  26. */
  27. public function deleteUser(ResourceControllerEvent $event): void
  28. {
  29. $user = $event->getSubject();
  30. Assert::isInstanceOf($user, UserInterface::class);
  31. if ($this->isTryingToDeleteLoggedInUser($user)) {
  32. $event->stopPropagation();
  33. $event->setErrorCode(Response::HTTP_UNPROCESSABLE_ENTITY);
  34. $event->setMessage('Cannot remove currently logged in user.');
  35. /** @var FlashBagInterface $flashBag */
  36. $flashBag = $this->session->getBag('flashes');
  37. $flashBag->add('error', 'Cannot remove currently logged in user.');
  38. }
  39. }
  40. private function isTryingToDeleteLoggedInUser(UserInterface $user): bool
  41. {
  42. $token = $this->tokenStorage->getToken();
  43. if (!$token) {
  44. return false;
  45. }
  46. $loggedUser = $token->getUser();
  47. if (!$loggedUser) {
  48. return false;
  49. }
  50. /** @var UserInterface $loggedUser */
  51. return $loggedUser->getId() === $user->getId() && $loggedUser->getRoles() === $user->getRoles();
  52. }
  53. }