CacheStorage.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /**
  3. * @copyright Vertex. All rights reserved. https://www.vertexinc.com/
  4. * @author Mediotype https://www.mediotype.com/
  5. */
  6. namespace Vertex\Tax\Model\TaxRegistry;
  7. use Magento\Framework\App\Cache\StateInterface;
  8. use Magento\Framework\Cache\FrontendInterface;
  9. use Vertex\Tax\Model\Cache\Type as CacheType;
  10. use Vertex\Tax\Model\Cache\Serializer;
  11. /**
  12. * Persistent storage for Vertex tax information.
  13. */
  14. class CacheStorage extends GenericStorage
  15. {
  16. const CACHE_ID_PREFIX = 'VERTEX_';
  17. /** @var FrontendInterface */
  18. private $cache;
  19. /** @var bool */
  20. private $enabled;
  21. /** @var SerializerInterface */
  22. private $serializer;
  23. /**
  24. * @param FrontendInterface $cache
  25. */
  26. public function __construct(
  27. FrontendInterface $cache,
  28. StateInterface $cacheState,
  29. Serializer $serializer
  30. ) {
  31. $this->cache = $cache;
  32. $this->enabled = $cacheState->isEnabled(CacheType::TYPE_IDENTIFIER);
  33. $this->serializer = $serializer;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function get($key, $default = null)
  39. {
  40. if (!$this->enabled) {
  41. return parent::get($key, $default);
  42. }
  43. $result = $this->cache->load($this->getCacheId($key));
  44. return $result === false ? $default : $this->unserialize($result);
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function set($key, $value, $lifetime = 0)
  50. {
  51. if (!$this->enabled) {
  52. return parent::set($key, $value, $lifetime);
  53. }
  54. return $this->cache->save($this->serialize($value), $this->getCacheId($key), [], $lifetime);
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function unsetData($key)
  60. {
  61. if (!$this->enabled) {
  62. return parent::unsetData($key);
  63. }
  64. $this->cache->remove($key);
  65. return $this->cache->load($key) === null;
  66. }
  67. /**
  68. * Generate a cache identifier from the given input.
  69. *
  70. * @param string $input
  71. * @return string
  72. */
  73. private function getCacheId($input)
  74. {
  75. return self::CACHE_ID_PREFIX . sha1($input);
  76. }
  77. /**
  78. * Serialize the given data.
  79. *
  80. * @param mixed $data
  81. * @return string
  82. */
  83. private function serialize($data)
  84. {
  85. return $this->serializer->serialize($data);
  86. }
  87. /**
  88. * Unserialize the given data.
  89. *
  90. * @param string $data
  91. * @return mixed
  92. */
  93. private function unserialize($data)
  94. {
  95. return $this->serializer->unserialize($data);
  96. }
  97. }