|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +namespace Magento\CatalogGraphQl\Model\Resolver\Products\SearchCriteria\CollectionProcessor\FilterProcessor; |
| 7 | + |
| 8 | +use Magento\Catalog\Model\CategoryFactory; |
| 9 | +use Magento\Catalog\Model\ResourceModel\Category as CategoryResourceModel; |
| 10 | +use Magento\Catalog\Model\ResourceModel\Product\Collection; |
| 11 | +use Magento\Framework\Api\Filter; |
| 12 | +use Magento\Framework\Api\SearchCriteria\CollectionProcessor\FilterProcessor\CustomFilterInterface; |
| 13 | +use Magento\Framework\Data\Collection\AbstractDb; |
| 14 | +use Magento\Framework\Exception\LocalizedException; |
| 15 | + |
| 16 | +/** |
| 17 | + * Category filter allows to filter products collection using 'category_id' filter from search criteria. |
| 18 | + */ |
| 19 | +class CategoryFilter implements CustomFilterInterface |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @var CategoryFactory |
| 23 | + */ |
| 24 | + private $categoryFactory; |
| 25 | + |
| 26 | + /** |
| 27 | + * @var CategoryResourceModel |
| 28 | + */ |
| 29 | + private $categoryResourceModel; |
| 30 | + |
| 31 | + /** |
| 32 | + * @param CategoryFactory $categoryFactory |
| 33 | + * @param CategoryResourceModel $categoryResourceModel |
| 34 | + */ |
| 35 | + public function __construct( |
| 36 | + CategoryFactory $categoryFactory, |
| 37 | + CategoryResourceModel $categoryResourceModel |
| 38 | + ) { |
| 39 | + $this->categoryFactory = $categoryFactory; |
| 40 | + $this->categoryResourceModel = $categoryResourceModel; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Apply filter by 'category_id' to product collection. |
| 45 | + * |
| 46 | + * For anchor categories, the products from all children categories will be present in the result. |
| 47 | + * |
| 48 | + * @param Filter $filter |
| 49 | + * @param AbstractDb $collection |
| 50 | + * @return bool Whether the filter is applied |
| 51 | + * @throws LocalizedException |
| 52 | + */ |
| 53 | + public function apply(Filter $filter, AbstractDb $collection) |
| 54 | + { |
| 55 | + $conditionType = $filter->getConditionType(); |
| 56 | + |
| 57 | + if ($conditionType !== 'eq') { |
| 58 | + throw new LocalizedException(__("'category_id' only supports 'eq' condition type.")); |
| 59 | + } |
| 60 | + |
| 61 | + $categoryId = $filter->getValue(); |
| 62 | + /** @var Collection $collection */ |
| 63 | + $category = $this->categoryFactory->create(); |
| 64 | + $this->categoryResourceModel->load($category, $categoryId); |
| 65 | + $collection->addCategoryFilter($category); |
| 66 | + |
| 67 | + return true; |
| 68 | + } |
| 69 | +} |
0 commit comments