vendor/symfony/security-core/Authentication/Token/Storage/UsageTrackingTokenStorage.php line 44

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 Symfony\Component\Security\Core\Authentication\Token\Storage;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  15. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  16. /**
  17. * A token storage that increments the session usage index when the token is accessed.
  18. *
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. final class UsageTrackingTokenStorage implements TokenStorageInterface, ServiceSubscriberInterface
  22. {
  23. private TokenStorageInterface $storage;
  24. private ContainerInterface $container;
  25. private bool $enableUsageTracking = false;
  26. public function __construct(TokenStorageInterface $storage, ContainerInterface $container)
  27. {
  28. $this->storage = $storage;
  29. $this->container = $container;
  30. }
  31. public function getToken(): ?TokenInterface
  32. {
  33. // reading the token can enable usage tracking, e.g. when a lazy firewall loads it from the session
  34. $token = $this->storage->getToken();
  35. if ($this->shouldTrackUsage()) {
  36. // increments the internal session usage index
  37. $this->getSession()->getMetadataBag();
  38. }
  39. return $token;
  40. }
  41. public function setToken(?TokenInterface $token = null): void
  42. {
  43. $this->storage->setToken($token);
  44. if ($token && $this->shouldTrackUsage()) {
  45. // increments the internal session usage index
  46. $this->getSession()->getMetadataBag();
  47. }
  48. }
  49. public function enableUsageTracking(): void
  50. {
  51. $this->enableUsageTracking = true;
  52. }
  53. public function disableUsageTracking(): void
  54. {
  55. $this->enableUsageTracking = false;
  56. }
  57. public static function getSubscribedServices(): array
  58. {
  59. return [
  60. 'request_stack' => RequestStack::class,
  61. ];
  62. }
  63. private function getSession(): SessionInterface
  64. {
  65. return $this->container->get('request_stack')->getSession();
  66. }
  67. private function shouldTrackUsage(): bool
  68. {
  69. return $this->enableUsageTracking && $this->container->get('request_stack')->getMainRequest();
  70. }
  71. }