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

  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 TokenStorageInterfaceServiceSubscriberInterface
  22. {
  23.     private TokenStorageInterface $storage;
  24.     private ContainerInterface $container;
  25.     private bool $enableUsageTracking false;
  26.     public function __construct(TokenStorageInterface $storageContainerInterface $container)
  27.     {
  28.         $this->storage $storage;
  29.         $this->container $container;
  30.     }
  31.     public function getToken(): ?TokenInterface
  32.     {
  33.         if ($this->shouldTrackUsage()) {
  34.             // increments the internal session usage index
  35.             $this->getSession()->getMetadataBag();
  36.         }
  37.         return $this->storage->getToken();
  38.     }
  39.     public function setToken(?TokenInterface $token null): void
  40.     {
  41.         $this->storage->setToken($token);
  42.         if ($token && $this->shouldTrackUsage()) {
  43.             // increments the internal session usage index
  44.             $this->getSession()->getMetadataBag();
  45.         }
  46.     }
  47.     public function enableUsageTracking(): void
  48.     {
  49.         $this->enableUsageTracking true;
  50.     }
  51.     public function disableUsageTracking(): void
  52.     {
  53.         $this->enableUsageTracking false;
  54.     }
  55.     public static function getSubscribedServices(): array
  56.     {
  57.         return [
  58.             'request_stack' => RequestStack::class,
  59.         ];
  60.     }
  61.     private function getSession(): SessionInterface
  62.     {
  63.         return $this->container->get('request_stack')->getSession();
  64.     }
  65.     private function shouldTrackUsage(): bool
  66.     {
  67.         return $this->enableUsageTracking && $this->container->get('request_stack')->getMainRequest();
  68.     }
  69. }