Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
EavAttributeCondition.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
14 
21 {
25  private $resourceConnection;
26 
30  private $eavConfig;
31 
36  public function __construct(
37  \Magento\Eav\Model\Config $eavConfig,
38  \Magento\Framework\App\ResourceConnection $resourceConnection
39  ) {
40  $this->eavConfig = $eavConfig;
41  $this->resourceConnection = $resourceConnection;
42  }
43 
52  public function build(Filter $filter): string
53  {
54  $attribute = $this->getAttributeByCode($filter->getField());
55  $tableAlias = 'ca_' . $attribute->getAttributeCode();
56 
57  $conditionType = $this->mapConditionType($filter->getConditionType());
58  $conditionValue = $this->mapConditionValue($conditionType, $filter->getValue());
59 
60  // NOTE: store scope was ignored intentionally to perform search across all stores
61  $attributeSelect = $this->resourceConnection->getConnection()
62  ->select()
63  ->from(
64  [$tableAlias => $attribute->getBackendTable()],
65  $tableAlias . '.' . $attribute->getEntityIdField()
66  )->where(
67  $this->resourceConnection->getConnection()->prepareSqlCondition(
68  $tableAlias . '.' . $attribute->getIdFieldName(),
69  ['eq' => $attribute->getAttributeId()]
70  )
71  )->where(
72  $this->resourceConnection->getConnection()->prepareSqlCondition(
73  $tableAlias . '.value',
74  [$conditionType => $conditionValue]
75  )
76  );
77 
78  return $this->resourceConnection
79  ->getConnection()
80  ->prepareSqlCondition(
81  Collection::MAIN_TABLE_ALIAS . '.' . $attribute->getEntityIdField(),
82  [
83  'in' => $attributeSelect
84  ]
85  );
86  }
87 
93  private function getAttributeByCode(string $field): Attribute
94  {
95  return $this->eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $field);
96  }
97 
104  private function mapConditionType(string $conditionType): string
105  {
106  $conditionsMap = [
107  'eq' => 'in',
108  'neq' => 'nin'
109  ];
110 
111  return isset($conditionsMap[$conditionType]) ? $conditionsMap[$conditionType] : $conditionType;
112  }
113 
121  private function mapConditionValue(string $conditionType, string $conditionValue): string
122  {
123  $conditionsMap = ['like', 'nlike'];
124 
125  if (in_array($conditionType, $conditionsMap)) {
126  $conditionValue = '%' . $conditionValue . '%';
127  }
128 
129  return $conditionValue;
130  }
131 }
__construct(\Magento\Eav\Model\Config $eavConfig, \Magento\Framework\App\ResourceConnection $resourceConnection)