Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SwatchAttributesProvider.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Swatches\Model;
7 
13 
18 {
22  private $typeConfigurable;
23 
27  private $swatchAttributeCodes;
28 
33  private $attributesPerProduct;
34 
38  private $swatchTypeChecker;
39 
45  public function __construct(
46  Configurable $typeConfigurable,
47  SwatchAttributeCodes $swatchAttributeCodes,
48  SwatchAttributeType $swatchTypeChecker = null
49  ) {
50  $this->typeConfigurable = $typeConfigurable;
51  $this->swatchAttributeCodes = $swatchAttributeCodes;
52  $this->swatchTypeChecker = $swatchTypeChecker
53  ?: ObjectManager::getInstance()->create(SwatchAttributeType::class);
54  }
55 
63  public function provide(Product $product)
64  {
65  if ($product->getTypeId() !== Configurable::TYPE_CODE) {
66  return [];
67  }
68  if (!isset($this->attributesPerProduct[$product->getId()])) {
69  $configurableAttributes = $this->typeConfigurable->getConfigurableAttributes($product);
70  $swatchAttributeCodeMap = $this->swatchAttributeCodes->getCodes();
71 
72  $swatchAttributes = [];
73  foreach ($configurableAttributes as $configurableAttribute) {
74  if (array_key_exists($configurableAttribute->getAttributeId(), $swatchAttributeCodeMap)) {
76  $productAttribute = $configurableAttribute->getProductAttribute();
77  if ($productAttribute !== null
78  && $this->swatchTypeChecker->isSwatchAttribute($productAttribute)
79  ) {
80  $swatchAttributes[$configurableAttribute->getAttributeId()] = $productAttribute;
81  }
82  }
83  }
84  $this->attributesPerProduct[$product->getId()] = $swatchAttributes;
85  }
86  return $this->attributesPerProduct[$product->getId()];
87  }
88 }
__construct(Configurable $typeConfigurable, SwatchAttributeCodes $swatchAttributeCodes, SwatchAttributeType $swatchTypeChecker=null)