Skip to content

Commit 45abb78

Browse files
committed
MAGETWO-62691: [Performance] EAV attributes caching optimization
1 parent 1505a44 commit 45abb78

File tree

1 file changed

+31
-6
lines changed
  • app/code/Magento/Swatches/Helper

1 file changed

+31
-6
lines changed

app/code/Magento/Swatches/Helper/Data.php

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -429,12 +429,13 @@ public function getSwatchAttributesAsArray(Product $product)
429429
*/
430430
public function getSwatchesByOptionsId(array $optionIds)
431431
{
432-
sort($optionIds);
433-
$cacheKey = implode('-', $optionIds);
434-
if (!isset($this->swatchesCache[$cacheKey])) {
432+
$swatches = $this->getCachedSwatches($optionIds);
433+
434+
if (count($swatches) !== count($optionIds)) {
435+
$swatchOptionIds = array_diff($optionIds, array_keys($swatches));
435436
/** @var \Magento\Swatches\Model\ResourceModel\Swatch\Collection $swatchCollection */
436437
$swatchCollection = $this->swatchCollectionFactory->create();
437-
$swatchCollection->addFilterByOptionsIds($optionIds);
438+
$swatchCollection->addFilterByOptionsIds($swatchOptionIds);
438439

439440
$swatches = [];
440441
$currentStoreId = $this->storeManager->getStore()->getId();
@@ -451,10 +452,34 @@ public function getSwatchesByOptionsId(array $optionIds)
451452
if (!empty($fallbackValues)) {
452453
$swatches = $this->addFallbackOptions($fallbackValues, $swatches);
453454
}
454-
$this->swatchesCache[$cacheKey] = $swatches;
455+
$this->setCachedSwatches($swatchOptionIds, $swatches);
455456
}
456457

457-
return $this->swatchesCache[$cacheKey];
458+
return array_filter($this->getCachedSwatches($optionIds));
459+
}
460+
461+
/**
462+
* Get cached swatches
463+
*
464+
* @param array $optionIds
465+
* @return array
466+
*/
467+
private function getCachedSwatches(array $optionIds)
468+
{
469+
return array_intersect_key($this->swatchesCache, array_combine($optionIds, $optionIds));
470+
}
471+
472+
/**
473+
* Cache swatch. If no swathes found for specific option id - set null for prevent double call
474+
*
475+
* @param array $optionIds
476+
* @param array $swatches
477+
*/
478+
private function setCachedSwatches(array $optionIds, array $swatches)
479+
{
480+
foreach ($optionIds as $optionId) {
481+
$this->swatchesCache[$optionId] = isset($swatches[$optionId]) ? $swatches[$optionId] : null;
482+
}
458483
}
459484

460485
/**

0 commit comments

Comments
 (0)