Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ConfigurableVariant.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
21 
26 {
30  private $variantCollection;
31 
35  private $optionCollection;
36 
40  private $valueFactory;
41 
45  private $attributeCollection;
46 
50  private $metadataPool;
51 
59  public function __construct(
60  Collection $variantCollection,
61  OptionCollection $optionCollection,
62  ValueFactory $valueFactory,
63  AttributeCollection $attributeCollection,
64  MetadataPool $metadataPool
65  ) {
66  $this->variantCollection = $variantCollection;
67  $this->optionCollection = $optionCollection;
68  $this->valueFactory = $valueFactory;
69  $this->attributeCollection = $attributeCollection;
70  $this->metadataPool = $metadataPool;
71  }
72 
78  public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
79  {
80  $linkField = $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField();
81  if ($value['type_id'] !== Type::TYPE_CODE || !isset($value[$linkField])) {
82  $result = function () {
83  return null;
84  };
85  return $this->valueFactory->create($result);
86  }
87 
88  $this->variantCollection->addParentId((int)$value[$linkField]);
89  $fields = $this->getProductFields($info);
90  $matchedFields = $this->attributeCollection->getRequestAttributes($fields);
91  $this->variantCollection->addEavAttributes($matchedFields);
92  $this->optionCollection->addProductId((int)$value[$linkField]);
93 
94  $result = function () use ($value, $linkField) {
95  $children = $this->variantCollection->getChildProductsByParentId((int)$value[$linkField]);
96  $options = $this->optionCollection->getAttributesByProductId((int)$value[$linkField]);
97  $variants = [];
99  foreach ($children as $key => $child) {
100  $variants[$key] = ['sku' => $child['sku'], 'product' => $child, 'options' => $options];
101  }
102 
103  return $variants;
104  };
105 
106  return $this->valueFactory->create($result);
107  }
108 
115  private function getProductFields(ResolveInfo $info)
116  {
117  $fieldNames = [];
118  foreach ($info->fieldNodes as $node) {
119  if ($node->name->value !== 'product') {
120  continue;
121  }
122 
123  foreach ($node->selectionSet->selections as $selectionNode) {
124  $fieldNames[] = $selectionNode->name->value;
125  }
126  }
127 
128  return $fieldNames;
129  }
130 }
$fields
Definition: details.phtml:14
__construct(Collection $variantCollection, OptionCollection $optionCollection, ValueFactory $valueFactory, AttributeCollection $attributeCollection, MetadataPool $metadataPool)
$value
Definition: gender.phtml:16
$children
Definition: actions.phtml:11
foreach( $_productCollection as $_product)() ?>" class $info
Definition: listing.phtml:52
resolve(Field $field, $context, ResolveInfo $info, array $value=null, array $args=null)