Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AttributeMetadataCache.php
Go to the documentation of this file.
1 <?php
7 
15 
20 {
24  const ATTRIBUTE_METADATA_CACHE_PREFIX = 'ATTRIBUTE_METADATA_INSTANCES_CACHE';
25 
29  private $cache;
30 
34  private $state;
35 
39  private $attributes;
40 
44  private $isAttributeCacheEnabled;
45 
49  private $attributeMetadataHydrator;
50 
54  private $serializer;
55 
64  public function __construct(
65  CacheInterface $cache,
66  StateInterface $state,
67  SerializerInterface $serializer,
68  AttributeMetadataHydrator $attributeMetadataHydrator
69  ) {
70  $this->cache = $cache;
71  $this->state = $state;
72  $this->serializer = $serializer;
73  $this->attributeMetadataHydrator = $attributeMetadataHydrator;
74  }
75 
83  public function load($entityType, $suffix = '')
84  {
85  if (isset($this->attributes[$entityType . $suffix])) {
86  return $this->attributes[$entityType . $suffix];
87  }
88  if ($this->isEnabled()) {
89  $cacheKey = self::ATTRIBUTE_METADATA_CACHE_PREFIX . $entityType . $suffix;
90  $serializedData = $this->cache->load($cacheKey);
91  if ($serializedData) {
92  $attributesData = $this->serializer->unserialize($serializedData);
93  $attributes = [];
94  foreach ($attributesData as $key => $attributeData) {
95  $attributes[$key] = $this->attributeMetadataHydrator->hydrate($attributeData);
96  }
97  $this->attributes[$entityType . $suffix] = $attributes;
98  return $attributes;
99  }
100  }
101  return false;
102  }
103 
112  public function save($entityType, array $attributes, $suffix = '')
113  {
114  $this->attributes[$entityType . $suffix] = $attributes;
115  if ($this->isEnabled()) {
116  $cacheKey = self::ATTRIBUTE_METADATA_CACHE_PREFIX . $entityType . $suffix;
117  $attributesData = [];
118  foreach ($attributes as $key => $attribute) {
119  $attributesData[$key] = $this->attributeMetadataHydrator->extract($attribute);
120  }
121  $serializedData = $this->serializer->serialize($attributesData);
122  $this->cache->save(
123  $serializedData,
124  $cacheKey,
125  [
129  ]
130  );
131  }
132  }
133 
139  public function clean()
140  {
141  unset($this->attributes);
142  if ($this->isEnabled()) {
143  $this->cache->clean(
144  [
147  ]
148  );
149  }
150  }
151 
157  private function isEnabled()
158  {
159  if (null === $this->isAttributeCacheEnabled) {
160  $this->isAttributeCacheEnabled = $this->state->isEnabled(Type::TYPE_IDENTIFIER);
161  }
162  return $this->isAttributeCacheEnabled;
163  }
164 }
$suffix
Definition: name.phtml:27
save($entityType, array $attributes, $suffix='')
$attributesData
$attributes
Definition: matrix.phtml:13
__construct(CacheInterface $cache, StateInterface $state, SerializerInterface $serializer, AttributeMetadataHydrator $attributeMetadataHydrator)