Attribute.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Plugin\Model\ResourceModel\Entity;
  7. use Magento\Eav\Model\Cache\Type;
  8. use Magento\Eav\Model\Entity\Attribute as EntityAttribute;
  9. use Magento\Eav\Model\ResourceModel\Entity\Attribute as AttributeResource;
  10. use Magento\Framework\App\Cache\StateInterface;
  11. use Magento\Framework\App\CacheInterface;
  12. use Magento\Framework\Serialize\SerializerInterface;
  13. class Attribute
  14. {
  15. /**
  16. * Cache key for store label attribute
  17. */
  18. const STORE_LABEL_ATTRIBUTE = 'EAV_STORE_LABEL_ATTRIBUTE';
  19. /**
  20. * @var CacheInterface
  21. */
  22. private $cache;
  23. /**
  24. * @var StateInterface
  25. */
  26. private $cacheState;
  27. /**
  28. * @var SerializerInterface
  29. */
  30. private $serializer;
  31. /**
  32. * @param CacheInterface $cache
  33. * @param StateInterface $cacheState
  34. * @param SerializerInterface $serializer
  35. * @codeCoverageIgnore
  36. */
  37. public function __construct(
  38. CacheInterface $cache,
  39. StateInterface $cacheState,
  40. SerializerInterface $serializer
  41. ) {
  42. $this->cache = $cache;
  43. $this->serializer = $serializer;
  44. $this->cacheState = $cacheState;
  45. }
  46. /**
  47. * @param AttributeResource $subject
  48. * @param callable $proceed
  49. * @param int $attributeId
  50. * @return array
  51. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  52. */
  53. public function aroundGetStoreLabelsByAttributeId(
  54. AttributeResource $subject,
  55. \Closure $proceed,
  56. $attributeId
  57. ) {
  58. $cacheId = self::STORE_LABEL_ATTRIBUTE . $attributeId;
  59. if ($this->isCacheEnabled() && ($storeLabels = $this->cache->load($cacheId))) {
  60. return $this->serializer->unserialize($storeLabels);
  61. }
  62. $storeLabels = $proceed($attributeId);
  63. if ($this->isCacheEnabled()) {
  64. $this->cache->save(
  65. $this->serializer->serialize($storeLabels),
  66. $cacheId,
  67. [
  68. Type::CACHE_TAG,
  69. EntityAttribute::CACHE_TAG
  70. ]
  71. );
  72. }
  73. return $storeLabels;
  74. }
  75. /**
  76. * Check if cache is enabled
  77. *
  78. * @return bool
  79. */
  80. private function isCacheEnabled()
  81. {
  82. return $this->cacheState->isEnabled(Type::TYPE_IDENTIFIER);
  83. }
  84. }