Advanced.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\CatalogSearch\Model;
  7. use Magento\Catalog\Model\Config;
  8. use Magento\Catalog\Model\Product\Visibility;
  9. use Magento\Catalog\Model\ProductFactory;
  10. use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
  11. use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory as AttributeCollectionFactory;
  12. use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
  13. use Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection as ProductCollection;
  14. use Magento\CatalogSearch\Model\ResourceModel\AdvancedFactory;
  15. use Magento\Directory\Model\CurrencyFactory;
  16. use Magento\Eav\Model\Entity\Attribute as EntityAttribute;
  17. use Magento\Framework\Model\Context;
  18. use Magento\Framework\Exception\LocalizedException;
  19. use Magento\Framework\Registry;
  20. use Magento\Store\Model\StoreManagerInterface;
  21. /**
  22. * Catalog advanced search model
  23. *
  24. * @method int getEntityTypeId()
  25. * @method \Magento\CatalogSearch\Model\Advanced setEntityTypeId(int $value)
  26. * @method int getAttributeSetId()
  27. * @method \Magento\CatalogSearch\Model\Advanced setAttributeSetId(int $value)
  28. * @method string getTypeId()
  29. * @method \Magento\CatalogSearch\Model\Advanced setTypeId(string $value)
  30. * @method string getSku()
  31. * @method \Magento\CatalogSearch\Model\Advanced setSku(string $value)
  32. * @method int getHasOptions()
  33. * @method \Magento\CatalogSearch\Model\Advanced setHasOptions(int $value)
  34. * @method int getRequiredOptions()
  35. * @method \Magento\CatalogSearch\Model\Advanced setRequiredOptions(int $value)
  36. * @method string getCreatedAt()
  37. * @method \Magento\CatalogSearch\Model\Advanced setCreatedAt(string $value)
  38. * @method string getUpdatedAt()
  39. * @method \Magento\CatalogSearch\Model\Advanced setUpdatedAt(string $value)
  40. *
  41. * @author Magento Core Team <core@magentocommerce.com>
  42. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  43. * @api
  44. * @since 100.0.2
  45. */
  46. class Advanced extends \Magento\Framework\Model\AbstractModel
  47. {
  48. /**
  49. * User friendly search criteria list
  50. *
  51. * @var array
  52. */
  53. protected $_searchCriterias = [];
  54. /**
  55. * Product collection
  56. *
  57. * @var ProductCollection
  58. */
  59. protected $_productCollection;
  60. /**
  61. * Initialize dependencies
  62. *
  63. * @var Config
  64. */
  65. protected $_catalogConfig;
  66. /**
  67. * Catalog product visibility
  68. *
  69. * @var Visibility
  70. */
  71. protected $_catalogProductVisibility;
  72. /**
  73. * Attribute collection factory
  74. *
  75. * @var AttributeCollectionFactory
  76. */
  77. protected $_attributeCollectionFactory;
  78. /**
  79. * Store manager
  80. *
  81. * @var \Magento\Store\Model\StoreManagerInterface
  82. */
  83. protected $_storeManager;
  84. /**
  85. * Product factory
  86. *
  87. * @var ProductFactory
  88. */
  89. protected $_productFactory;
  90. /**
  91. * Currency factory
  92. *
  93. * @var CurrencyFactory
  94. */
  95. protected $_currencyFactory;
  96. /**
  97. * Advanced Collection Factory
  98. *
  99. * @var ProductCollectionFactory
  100. */
  101. protected $productCollectionFactory;
  102. /**
  103. * Construct
  104. *
  105. * @param Context $context
  106. * @param Registry $registry
  107. * @param AttributeCollectionFactory $attributeCollectionFactory
  108. * @param Visibility $catalogProductVisibility
  109. * @param Config $catalogConfig
  110. * @param CurrencyFactory $currencyFactory
  111. * @param ProductFactory $productFactory
  112. * @param StoreManagerInterface $storeManager
  113. * @param ProductCollectionFactory $productCollectionFactory
  114. * @param AdvancedFactory $advancedFactory
  115. * @param array $data
  116. *
  117. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  118. */
  119. public function __construct(
  120. Context $context,
  121. Registry $registry,
  122. AttributeCollectionFactory $attributeCollectionFactory,
  123. Visibility $catalogProductVisibility,
  124. Config $catalogConfig,
  125. CurrencyFactory $currencyFactory,
  126. ProductFactory $productFactory,
  127. StoreManagerInterface $storeManager,
  128. ProductCollectionFactory $productCollectionFactory,
  129. AdvancedFactory $advancedFactory,
  130. array $data = []
  131. ) {
  132. $this->_attributeCollectionFactory = $attributeCollectionFactory;
  133. $this->_catalogProductVisibility = $catalogProductVisibility;
  134. $this->_catalogConfig = $catalogConfig;
  135. $this->_currencyFactory = $currencyFactory;
  136. $this->_productFactory = $productFactory;
  137. $this->_storeManager = $storeManager;
  138. $this->productCollectionFactory = $productCollectionFactory;
  139. parent::__construct(
  140. $context,
  141. $registry,
  142. $advancedFactory->create(),
  143. $this->productCollectionFactory->create(),
  144. $data
  145. );
  146. }
  147. /**
  148. * Add advanced search filters to product collection
  149. *
  150. * @param array $values
  151. * @return $this
  152. * @throws LocalizedException
  153. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  154. * @SuppressWarnings(PHPMD.NPathComplexity)
  155. */
  156. public function addFilters($values)
  157. {
  158. $attributes = $this->getAttributes();
  159. $allConditions = [];
  160. foreach ($attributes as $attribute) {
  161. /* @var $attribute Attribute */
  162. if (!isset($values[$attribute->getAttributeCode()])) {
  163. continue;
  164. }
  165. $value = $values[$attribute->getAttributeCode()];
  166. $preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
  167. if (false === $preparedSearchValue) {
  168. continue;
  169. }
  170. $this->addSearchCriteria($attribute, $preparedSearchValue);
  171. if ($attribute->getAttributeCode() == 'price') {
  172. $rate = 1;
  173. $store = $this->_storeManager->getStore();
  174. $currency = $store->getCurrentCurrencyCode();
  175. if ($currency != $store->getBaseCurrencyCode()) {
  176. $rate = $store->getBaseCurrency()->getRate($currency);
  177. }
  178. $value['from'] = (isset($value['from']) && is_numeric($value['from']))
  179. ? (float)$value['from'] / $rate
  180. : '';
  181. $value['to'] = (isset($value['to']) && is_numeric($value['to']))
  182. ? (float)$value['to'] / $rate
  183. : '';
  184. }
  185. if ($attribute->getBackendType() == 'datetime') {
  186. $value['from'] = (isset($value['from']) && !empty($value['from']))
  187. ? date('Y-m-d\TH:i:s\Z', strtotime($value['from']))
  188. : '';
  189. $value['to'] = (isset($value['to']) && !empty($value['to']))
  190. ? date('Y-m-d\TH:i:s\Z', strtotime($value['to']))
  191. : '';
  192. }
  193. $condition = $this->_getResource()->prepareCondition(
  194. $attribute,
  195. $value,
  196. $this->getProductCollection()
  197. );
  198. if ($condition === false) {
  199. continue;
  200. }
  201. $table = $attribute->getBackend()->getTable();
  202. if ($attribute->getBackendType() == 'static') {
  203. $attributeId = $attribute->getAttributeCode();
  204. } else {
  205. $attributeId = $attribute->getId();
  206. }
  207. $allConditions[$table][$attributeId] = $condition;
  208. }
  209. if ($allConditions) {
  210. $this->_registry->register('advanced_search_conditions', $allConditions);
  211. $this->getProductCollection()->addFieldsToFilter($allConditions);
  212. } else {
  213. throw new LocalizedException(__('Enter a search term and try again.'));
  214. }
  215. return $this;
  216. }
  217. /**
  218. * Retrieve array of attributes used in advanced search
  219. *
  220. * @return array|\Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection
  221. */
  222. public function getAttributes()
  223. {
  224. $attributes = $this->getData('attributes');
  225. if ($attributes === null) {
  226. $product = $this->_productFactory->create();
  227. $attributes = $this->_attributeCollectionFactory
  228. ->create()
  229. ->addHasOptionsFilter()
  230. ->addDisplayInAdvancedSearchFilter()
  231. ->addStoreLabel($this->_storeManager->getStore()->getId())
  232. ->setOrder('main_table.attribute_id', 'asc')
  233. ->load();
  234. foreach ($attributes as $attribute) {
  235. $attribute->setEntity($product->getResource());
  236. }
  237. $this->setData('attributes', $attributes);
  238. }
  239. return $attributes;
  240. }
  241. /**
  242. * Retrieve advanced search product collection
  243. *
  244. * @return Collection
  245. */
  246. public function getProductCollection()
  247. {
  248. if ($this->_productCollection === null) {
  249. $collection = $this->productCollectionFactory->create();
  250. $this->prepareProductCollection($collection);
  251. if (!$collection) {
  252. return $collection;
  253. }
  254. $this->_productCollection = $collection;
  255. }
  256. return $this->_productCollection;
  257. }
  258. /**
  259. * Prepare product collection
  260. *
  261. * @param Collection $collection
  262. * @return $this
  263. */
  264. public function prepareProductCollection($collection)
  265. {
  266. $collection
  267. ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
  268. ->setStore($this->_storeManager->getStore())
  269. ->addMinimalPrice()
  270. ->addTaxPercents()
  271. ->addStoreFilter()
  272. ->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
  273. return $this;
  274. }
  275. /**
  276. * Add search criteria.
  277. *
  278. * @param EntityAttribute $attribute
  279. * @param mixed $value
  280. * @return void
  281. */
  282. protected function addSearchCriteria($attribute, $value)
  283. {
  284. if (!empty($value)) {
  285. $this->_searchCriterias[] = ['name' => $attribute->getStoreLabel(), 'value' => $value];
  286. }
  287. }
  288. /**
  289. * Add data about search criteria to object state
  290. *
  291. * @todo: Move this code to block
  292. *
  293. * @param EntityAttribute $attribute
  294. * @param mixed $value
  295. * @return string|bool
  296. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  297. * @SuppressWarnings(PHPMD.NPathComplexity)
  298. */
  299. protected function getPreparedSearchCriteria($attribute, $value)
  300. {
  301. if (is_array($value)) {
  302. if (isset($value['from']) && isset($value['to'])) {
  303. if (!empty($value['from']) || !empty($value['to'])) {
  304. if (isset($value['currency'])) {
  305. /** @var $currencyModel Currency */
  306. $currencyModel = $this->_currencyFactory->create()->load($value['currency']);
  307. $from = $currencyModel->format($value['from'], [], false);
  308. $to = $currencyModel->format($value['to'], [], false);
  309. } else {
  310. $currencyModel = null;
  311. }
  312. if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
  313. // -
  314. $value = sprintf(
  315. '%s - %s',
  316. $currencyModel ? $from : $value['from'],
  317. $currencyModel ? $to : $value['to']
  318. );
  319. } elseif (strlen($value['from']) > 0) {
  320. // and more
  321. $value = __('%1 and greater', $currencyModel ? $from : $value['from']);
  322. } elseif (strlen($value['to']) > 0) {
  323. // to
  324. $value = __('up to %1', $currencyModel ? $to : $value['to']);
  325. }
  326. } else {
  327. return '';
  328. }
  329. }
  330. }
  331. if (($attribute->getFrontendInput() == 'select' ||
  332. $attribute->getFrontendInput() == 'multiselect') && is_array($value)
  333. ) {
  334. foreach ($value as $key => $val) {
  335. $value[$key] = $attribute->getSource()->getOptionText($val);
  336. if (is_array($value[$key])) {
  337. $value[$key] = $value[$key]['label'];
  338. }
  339. }
  340. $value = implode(', ', $value);
  341. } elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
  342. $value = $attribute->getSource()->getOptionText($value);
  343. if (is_array($value)) {
  344. $value = $value['label'];
  345. }
  346. } elseif ($attribute->getFrontendInput() == 'boolean') {
  347. if (is_numeric($value)) {
  348. $value = $value == 1 ? __('Yes') : __('No');
  349. } else {
  350. $value = false;
  351. }
  352. }
  353. return $value;
  354. }
  355. /**
  356. * Returns prepared search criterias in text
  357. *
  358. * @return array
  359. */
  360. public function getSearchCriterias()
  361. {
  362. return $this->_searchCriterias;
  363. }
  364. }