Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductCategoryCondition.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
14 use Magento\Framework\Exception\NoSuchEntityException as CategoryDoesNotExistException;
15 
22 {
26  private $resourceConnection;
27 
31  private $categoryRepository;
32 
37  private $rootCategoryLevel = 1;
38 
42  public function __construct(
43  \Magento\Framework\App\ResourceConnection $resourceConnection,
44  \Magento\Catalog\Model\CategoryRepository $categoryRepository
45  ) {
46  $this->resourceConnection = $resourceConnection;
47  $this->categoryRepository = $categoryRepository;
48  }
49 
56  public function build(Filter $filter): string
57  {
58  $categorySelect = $this->resourceConnection->getConnection()->select()
59  ->from(
60  ['cat' => $this->resourceConnection->getTableName('catalog_category_product')],
61  'cat.product_id'
62  )->where(
63  $this->resourceConnection->getConnection()->prepareSqlCondition(
64  'cat.category_id',
65  [$this->mapConditionType($filter->getConditionType()) => $this->getCategoryIds($filter)]
66  )
67  );
68 
69  $selectCondition = [
70  'in' => $categorySelect
71  ];
72 
73  return $this->resourceConnection->getConnection()
74  ->prepareSqlCondition(Collection::MAIN_TABLE_ALIAS . '.entity_id', $selectCondition);
75  }
76 
85  private function getCategoryIds(Filter $filter): array
86  {
87  $categoryIds = explode(',', $filter->getValue());
88  $childCategoryIds = [];
89 
90  foreach ($categoryIds as $categoryId) {
91  try {
92  $category = $this->categoryRepository->get($categoryId);
93  } catch (CategoryDoesNotExistException $exception) {
94  continue;
95  }
96 
97  if ($category->getIsAnchor()) {
98  $childCategoryIds[] = $category->getAllChildren(true);
99  }
100 
101  // This is the simplest way to check if category is root
102  if ((int)$category->getLevel() === $this->rootCategoryLevel) {
103  $childCategoryIds[] = $category->getAllChildren(true);
104  }
105  }
106 
107  return array_unique(array_merge($categoryIds, ...$childCategoryIds));
108  }
109 
116  private function mapConditionType(string $conditionType): string
117  {
118  $conditionsMap = [
119  'eq' => 'in',
120  'neq' => 'nin',
121  'like' => 'in',
122  'nlike' => 'nin',
123  ];
124  return $conditionsMap[$conditionType] ?? $conditionType;
125  }
126 }
__construct(\Magento\Framework\App\ResourceConnection $resourceConnection, \Magento\Catalog\Model\CategoryRepository $categoryRepository)