CacheClassMetadataFactory.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\Serializer\Mapping\Factory;
  11. use Psr\Cache\CacheItemPoolInterface;
  12. /**
  13. * Caches metadata using a PSR-6 implementation.
  14. *
  15. * @author Kévin Dunglas <dunglas@gmail.com>
  16. */
  17. class CacheClassMetadataFactory implements ClassMetadataFactoryInterface
  18. {
  19. use ClassResolverTrait;
  20. /**
  21. * @var ClassMetadataFactoryInterface
  22. */
  23. private $decorated;
  24. /**
  25. * @var CacheItemPoolInterface
  26. */
  27. private $cacheItemPool;
  28. private $loadedClasses = [];
  29. public function __construct(ClassMetadataFactoryInterface $decorated, CacheItemPoolInterface $cacheItemPool)
  30. {
  31. $this->decorated = $decorated;
  32. $this->cacheItemPool = $cacheItemPool;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function getMetadataFor($value)
  38. {
  39. $class = $this->getClass($value);
  40. if (isset($this->loadedClasses[$class])) {
  41. return $this->loadedClasses[$class];
  42. }
  43. $key = rawurlencode(strtr($class, '\\', '_'));
  44. $item = $this->cacheItemPool->getItem($key);
  45. if ($item->isHit()) {
  46. return $this->loadedClasses[$class] = $item->get();
  47. }
  48. $metadata = $this->decorated->getMetadataFor($value);
  49. $this->cacheItemPool->save($item->set($metadata));
  50. return $this->loadedClasses[$class] = $metadata;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function hasMetadataFor($value)
  56. {
  57. return $this->decorated->hasMetadataFor($value);
  58. }
  59. }