CacheClassMetadataFactory.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. public function __construct(ClassMetadataFactoryInterface $decorated, CacheItemPoolInterface $cacheItemPool)
  29. {
  30. $this->decorated = $decorated;
  31. $this->cacheItemPool = $cacheItemPool;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function getMetadataFor($value)
  37. {
  38. $class = $this->getClass($value);
  39. // Key cannot contain backslashes according to PSR-6
  40. $key = strtr($class, '\\', '_');
  41. $item = $this->cacheItemPool->getItem($key);
  42. if ($item->isHit()) {
  43. return $item->get();
  44. }
  45. $metadata = $this->decorated->getMetadataFor($value);
  46. $this->cacheItemPool->save($item->set($metadata));
  47. return $metadata;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function hasMetadataFor($value)
  53. {
  54. return $this->decorated->hasMetadataFor($value);
  55. }
  56. }