-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
ListProduct.php
511 lines (451 loc) · 13.9 KB
/
ListProduct.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Block\Product;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Block\Product\ProductList\Toolbar;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Config;
use Magento\Catalog\Model\Layer;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Config\Element;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Url\Helper\Data;
/**
* Product list
* @api
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
*/
class ListProduct extends AbstractProduct implements IdentityInterface
{
/**
* Default toolbar block name
*
* @var string
*/
protected $_defaultToolbarBlock = Toolbar::class;
/**
* Product Collection
*
* @var AbstractCollection
*/
protected $_productCollection;
/**
* Catalog layer
*
* @var Layer
*/
protected $_catalogLayer;
/**
* @var PostHelper
*/
protected $_postDataHelper;
/**
* @var Data
*/
protected $urlHelper;
/**
* @var CategoryRepositoryInterface
*/
protected $categoryRepository;
/**
* @param Context $context
* @param PostHelper $postDataHelper
* @param Resolver $layerResolver
* @param CategoryRepositoryInterface $categoryRepository
* @param Data $urlHelper
* @param array $data
*/
public function __construct(
Context $context,
PostHelper $postDataHelper,
Resolver $layerResolver,
CategoryRepositoryInterface $categoryRepository,
Data $urlHelper,
array $data = []
) {
$this->_catalogLayer = $layerResolver->get();
$this->_postDataHelper = $postDataHelper;
$this->categoryRepository = $categoryRepository;
$this->urlHelper = $urlHelper;
parent::__construct(
$context,
$data
);
}
/**
* Retrieve loaded product collection
*
* The goal of this method is to choose whether the existing collection should be returned
* or a new one should be initialized.
*
* It is not just a caching logic, but also is a real logical check
* because there are two ways how collection may be stored inside the block:
* - Product collection may be passed externally by 'setCollection' method
* - Product collection may be requested internally from the current Catalog Layer.
*
* And this method will return collection anyway,
* even when it did not pass externally and therefore isn't cached yet
*
* @return AbstractCollection
*/
protected function _getProductCollection()
{
if ($this->_productCollection === null) {
$this->_productCollection = $this->initializeProductCollection();
}
return $this->_productCollection;
}
/**
* Get catalog layer model
*
* @return Layer
*/
public function getLayer()
{
return $this->_catalogLayer;
}
/**
* Retrieve loaded category collection
*
* @return AbstractCollection
*/
public function getLoadedProductCollection()
{
return $this->_getProductCollection();
}
/**
* Retrieve current view mode
*
* @return string
*/
public function getMode()
{
if ($this->getChildBlock('toolbar')) {
return $this->getChildBlock('toolbar')->getCurrentMode();
}
return $this->getDefaultListingMode();
}
/**
* Get listing mode for products if toolbar is removed from layout.
* Use the general configuration for product list mode from config path catalog/frontend/list_mode as default value
* or mode data from block declaration from layout.
*
* @return string
*/
private function getDefaultListingMode()
{
// default Toolbar when the toolbar layout is not used
$defaultToolbar = $this->getToolbarBlock();
$availableModes = $defaultToolbar->getModes();
// layout config mode
$mode = $this->getData('mode');
if (!$mode || !isset($availableModes[$mode])) {
// default config mode
$mode = $defaultToolbar->getCurrentMode();
}
return $mode;
}
/**
* Need use as _prepareLayout - but problem in declaring collection from
* another block (was problem with search result)
* @return $this
*/
protected function _beforeToHtml()
{
$collection = $this->_getProductCollection();
$this->addToolbarBlock($collection);
$collection->load();
return parent::_beforeToHtml();
}
/**
* Add toolbar block from product listing layout
*
* @param Collection $collection
*/
private function addToolbarBlock(Collection $collection)
{
$toolbarLayout = $this->getToolbarFromLayout();
if ($toolbarLayout) {
$this->configureToolbar($toolbarLayout, $collection);
}
}
/**
* Retrieve Toolbar block from layout or a default Toolbar
*
* @return Toolbar
*/
public function getToolbarBlock()
{
$block = $this->getToolbarFromLayout();
if (!$block) {
$block = $this->getLayout()->createBlock($this->_defaultToolbarBlock, uniqid(microtime()));
}
return $block;
}
/**
* Get toolbar block from layout
*
* @return bool|Toolbar
*/
private function getToolbarFromLayout()
{
$blockName = $this->getToolbarBlockName();
$toolbarLayout = false;
if ($blockName) {
$toolbarLayout = $this->getLayout()->getBlock($blockName);
}
return $toolbarLayout;
}
/**
* Retrieve additional blocks html
*
* @return string
*/
public function getAdditionalHtml()
{
return $this->getChildHtml('additional');
}
/**
* Retrieve list toolbar HTML
*
* @return string
*/
public function getToolbarHtml()
{
return $this->getChildHtml('toolbar');
}
/**
* @param AbstractCollection $collection
* @return $this
*/
public function setCollection($collection)
{
$this->_productCollection = $collection;
return $this;
}
/**
* @param array|string|integer| Element $code
* @return $this
*/
public function addAttribute($code)
{
$this->_getProductCollection()->addAttributeToSelect($code);
return $this;
}
/**
* @return mixed
*/
public function getPriceBlockTemplate()
{
return $this->_getData('price_block_template');
}
/**
* Retrieve Catalog Config object
*
* @return Config
*/
protected function _getConfig()
{
return $this->_catalogConfig;
}
/**
* Prepare Sort By fields from Category Data
*
* @param Category $category
* @return $this
*/
public function prepareSortableFieldsByCategory($category)
{
if (!$this->getAvailableOrders()) {
$this->setAvailableOrders($category->getAvailableSortByOptions());
}
$availableOrders = $this->getAvailableOrders();
if (!$this->getSortBy()) {
$categorySortBy = $this->getDefaultSortBy() ?: $category->getDefaultSortBy();
if ($categorySortBy) {
if (!$availableOrders) {
$availableOrders = $this->_getConfig()->getAttributeUsedForSortByArray();
}
if (isset($availableOrders[$categorySortBy])) {
$this->setSortBy($categorySortBy);
}
}
}
return $this;
}
/**
* Return identifiers for produced content
*
* @return array
*/
public function getIdentities()
{
$identities = [];
$category = $this->getLayer()->getCurrentCategory();
if ($category) {
$identities[] = Product::CACHE_PRODUCT_CATEGORY_TAG . '_' . $category->getId();
}
//Check if category page shows only static block (No products)
if ($category->getData('display_mode') == Category::DM_PAGE) {
return $identities;
}
foreach ($this->_getProductCollection() as $item) {
$identities = array_merge($identities, $item->getIdentities());
}
return $identities;
}
/**
* Get post parameters
*
* @param Product $product
* @return string
*/
public function getAddToCartPostParams(Product $product)
{
$url = $this->getAddToCartUrl($product);
return [
'action' => $url,
'data' => [
'product' => $product->getEntityId(),
ActionInterface::PARAM_NAME_URL_ENCODED => $this->urlHelper->getEncodedUrl($url),
]
];
}
/**
* @param Product $product
* @return string
*/
public function getProductPrice(Product $product)
{
$priceRender = $this->getPriceRender();
$price = '';
if ($priceRender) {
$price = $priceRender->render(
FinalPrice::PRICE_CODE,
$product,
[
'include_container' => true,
'display_minimal_price' => true,
'zone' => Render::ZONE_ITEM_LIST,
'list_category_page' => true
]
);
}
return $price;
}
/**
* Specifies that price rendering should be done for the list of products
* i.e. rendering happens in the scope of product list, but not single product
*
* @return Render
*/
protected function getPriceRender()
{
return $this->getLayout()->getBlock('product.price.render.default')
->setData('is_product_list', true);
}
/**
* Configures product collection from a layer and returns its instance.
*
* Also in the scope of a product collection configuration, this method initiates configuration of Toolbar.
* The reason to do this is because we have a bunch of legacy code
* where Toolbar configures several options of a collection and therefore this block depends on the Toolbar.
*
* This dependency leads to a situation where Toolbar sometimes called to configure a product collection,
* and sometimes not.
*
* To unify this behavior and prevent potential bugs this dependency is explicitly called
* when product collection initialized.
*
* @return Collection
*/
private function initializeProductCollection()
{
$layer = $this->getLayer();
/* @var $layer Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId($this->_storeManager->getStore()->getRootCategoryId());
}
// if this is a product view page
if ($this->_coreRegistry->registry('product')) {
// get collection of categories this product is associated with
$categories = $this->_coreRegistry->registry('product')
->getCategoryCollection()->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator())->getId());
}
}
$origCategory = null;
if ($this->getCategoryId()) {
try {
$category = $this->categoryRepository->get($this->getCategoryId());
} catch (NoSuchEntityException $e) {
$category = null;
}
if ($category) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$collection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
$this->addToolbarBlock($collection);
$this->_eventManager->dispatch(
'catalog_block_product_list_collection',
['collection' => $collection]
);
return $collection;
}
/**
* Configures the Toolbar block with options from this block and configured product collection.
*
* The purpose of this method is the one-way sharing of different sorting related data
* between this block, which is responsible for product list rendering,
* and the Toolbar block, whose responsibility is a rendering of these options.
*
* @param ProductList\Toolbar $toolbar
* @param Collection $collection
* @return void
*/
private function configureToolbar(Toolbar $toolbar, Collection $collection)
{
// use sortable parameters
$orders = $this->getAvailableOrders();
if ($orders) {
$toolbar->setAvailableOrders($orders);
}
$sort = $this->getSortBy();
if ($sort) {
$toolbar->setDefaultOrder($sort);
}
$dir = $this->getDefaultDirection();
if ($dir) {
$toolbar->setDefaultDirection($dir);
}
$modes = $this->getModes();
if ($modes) {
$toolbar->setModes($modes);
}
// set collection to toolbar and apply sort
$toolbar->setCollection($collection);
$this->setChild('toolbar', $toolbar);
}
}