|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace Magento\PageBuilder\Model\Catalog; |
| 10 | + |
| 11 | +/** |
| 12 | + * Sorting of Catalog Widget Products |
| 13 | + */ |
| 14 | +class Sorting |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @var array |
| 18 | + */ |
| 19 | + private $sortClasses; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var Sorting\Factory |
| 23 | + */ |
| 24 | + private $factory; |
| 25 | + |
| 26 | + /** |
| 27 | + * @var Sorting\OptionInterface[] |
| 28 | + */ |
| 29 | + private $sortInstances = []; |
| 30 | + |
| 31 | + /** |
| 32 | + * @param Sorting\Factory $factory |
| 33 | + * @param array $sortClasses |
| 34 | + * @throws \Magento\Framework\Exception\LocalizedException |
| 35 | + */ |
| 36 | + public function __construct( |
| 37 | + Sorting\Factory $factory, |
| 38 | + array $sortClasses |
| 39 | + ) { |
| 40 | + $this->sortClasses = $sortClasses; |
| 41 | + $this->factory = $factory; |
| 42 | + foreach ($this->sortClasses as $key => $className) { |
| 43 | + $this->sortInstances[$key] = $this->factory->create($className); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Sorting options array |
| 49 | + * |
| 50 | + * @return array |
| 51 | + */ |
| 52 | + public function getSortingOptions(): array |
| 53 | + { |
| 54 | + $options = []; |
| 55 | + foreach ($this->sortInstances as $key => $instance) { |
| 56 | + $options[$key] = $instance->getLabel(); |
| 57 | + } |
| 58 | + return $options; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Get the instance of the first option which is None |
| 63 | + * |
| 64 | + * @param string $sortOption |
| 65 | + * @return Sorting\OptionInterface |
| 66 | + */ |
| 67 | + public function getSortingInstance($sortOption): Sorting\OptionInterface |
| 68 | + { |
| 69 | + if (isset($this->sortInstances[$sortOption])) { |
| 70 | + return $this->sortInstances[$sortOption]; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Applying sorting option |
| 76 | + * |
| 77 | + * @param string $option |
| 78 | + * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection |
| 79 | + * @return \Magento\Catalog\Model\ResourceModel\Product\Collection |
| 80 | + */ |
| 81 | + public function applySorting( |
| 82 | + string $option, |
| 83 | + \Magento\Catalog\Model\ResourceModel\Product\Collection $collection |
| 84 | + ): \Magento\Catalog\Model\ResourceModel\Product\Collection { |
| 85 | + $sortBuilder = $this->getSortingInstance($option); |
| 86 | + $_collection = $sortBuilder->sort($collection); |
| 87 | + |
| 88 | + if ($_collection->isLoaded()) { |
| 89 | + $_collection->clear(); |
| 90 | + } |
| 91 | + |
| 92 | + return $_collection; |
| 93 | + } |
| 94 | +} |
0 commit comments