Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductImage.php
Go to the documentation of this file.
1 <?php
7 
16 
21 {
26  const CATEGORY_PAGE_GRID_LOCATION = 'category_page_grid';
27  const CATEGORY_PAGE_LIST_LOCATION = 'category_page_list';
28 
34  protected $swatchHelperData;
35 
39  protected $eavConfig;
40 
44  protected $request;
45 
51  public function __construct(
52  Data $swatchesHelperData,
55  ) {
56  $this->swatchHelperData = $swatchesHelperData;
57  $this->eavConfig = $eavConfig;
58  $this->request = $request;
59  }
60 
71  public function beforeGetImage(
72  AbstractProduct $subject,
74  $location,
75  array $attributes = []
76  ) {
77  if ($product->getTypeId() == Configurable::TYPE_CODE
78  && ($location == self::CATEGORY_PAGE_GRID_LOCATION || $location == self::CATEGORY_PAGE_LIST_LOCATION)) {
79  $request = $this->request->getParams();
80  if (is_array($request)) {
81  $filterArray = $this->getFilterArray($request, $product);
82  if (!empty($filterArray)) {
83  $product = $this->loadSimpleVariation($product, $filterArray);
84  }
85  }
86  }
87  return [$product, $location, $attributes];
88  }
89 
95  private function loadSimpleVariation(Product $parentProduct, array $filterArray)
96  {
97  $childProduct = $this->swatchHelperData->loadVariationByFallback($parentProduct, $filterArray);
98  if ($childProduct && !$childProduct->getImage()) {
99  $childProduct = $this->swatchHelperData->loadFirstVariationWithImage($parentProduct, $filterArray);
100  }
101  if (!$childProduct) {
102  $childProduct = $parentProduct;
103  }
104  return $childProduct;
105  }
106 
114  private function getFilterArray(array $request, Product $product)
115  {
116  $filterArray = [];
117  $attributes = $this->eavConfig->getEntityAttributes(Product::ENTITY, $product);
118  foreach ($request as $code => $value) {
119  if (isset($attributes[$code])) {
121  if ($this->canReplaceImageWithSwatch($attribute)) {
122  $filterArray[$code] = $value;
123  }
124  }
125  }
126  return $filterArray;
127  }
128 
135  private function canReplaceImageWithSwatch($attribute)
136  {
137  $result = true;
138  if (!$this->swatchHelperData->isSwatchAttribute($attribute)) {
139  $result = false;
140  }
141 
142  if (!$attribute->getUsedInProductListing()
143  || !$attribute->getIsFilterable()
144  || !$attribute->getData('update_product_preview_image')
145  ) {
146  $result = false;
147  }
148 
149  return $result;
150  }
151 }
__construct(Data $swatchesHelperData, Config $eavConfig, Http $request)
$value
Definition: gender.phtml:16
$attributes
Definition: matrix.phtml:13
beforeGetImage(AbstractProduct $subject, ProductModel $product, $location, array $attributes=[])
$code
Definition: info.phtml:12