Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Collection.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
12 use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\CollectionFactory;
16 use Magento\Catalog\Model\ProductFactory;
18 
23 {
27  private $attributeCollectionFactory;
28 
32  private $productFactory;
33 
37  private $metadataPool;
38 
42  private $productIds = [];
43 
47  private $attributeMap = [];
48 
54  public function __construct(
55  CollectionFactory $attributeCollectionFactory,
56  ProductFactory $productFactory,
57  MetadataPool $metadataPool
58  ) {
59  $this->attributeCollectionFactory = $attributeCollectionFactory;
60  $this->productFactory = $productFactory;
61  $this->metadataPool = $metadataPool;
62  }
63 
69  public function addProductId(int $productId) : void
70  {
71  if (!in_array($productId, $this->productIds)) {
72  $this->productIds[] = $productId;
73  }
74  }
75 
82  public function getAttributesByProductId(int $productId) : array
83  {
84  $attributes = $this->fetch();
85 
86  if (!isset($attributes[$productId])) {
87  return [];
88  }
89 
90  return $attributes[$productId];
91  }
92 
98  private function fetch() : array
99  {
100  if (empty($this->productIds) || !empty($this->attributeMap)) {
101  return $this->attributeMap;
102  }
103 
104  $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField();
106  $attributeCollection = $this->attributeCollectionFactory->create();
107  foreach ($this->productIds as $id) {
109  $product = $this->productFactory->create();
110  $product->setData($linkField, $id);
111  $attributeCollection->setProductFilter($product);
112  }
113 
115  foreach ($attributeCollection->getItems() as $attribute) {
116  $productId = (int)$attribute->getProductId();
117  if (!isset($this->attributeMap[$productId])) {
118  $this->attributeMap[$productId] = [];
119  }
120 
121  $attributeData = $attribute->getData();
122  $this->attributeMap[$productId][$attribute->getId()] = $attribute->getData();
123  $this->attributeMap[$productId][$attribute->getId()]['id'] = $attribute->getId();
124  $this->attributeMap[$productId][$attribute->getId()]['attribute_code']
125  = $attribute->getProductAttribute()->getAttributeCode();
126  $this->attributeMap[$productId][$attribute->getId()]['values'] = $attributeData['options'];
127  }
128 
129  return $this->attributeMap;
130  }
131 }
$id
Definition: fieldset.phtml:14
__construct(CollectionFactory $attributeCollectionFactory, ProductFactory $productFactory, MetadataPool $metadataPool)
Definition: Collection.php:54
$attributes
Definition: matrix.phtml:13