DataProvider.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\CatalogSearch\Model\Autocomplete;
  7. use Magento\Search\Model\ResourceModel\Query\Collection;
  8. use Magento\Search\Model\QueryFactory;
  9. use Magento\Search\Model\Autocomplete\DataProviderInterface;
  10. use Magento\Search\Model\Autocomplete\ItemFactory;
  11. use Magento\Framework\App\Config\ScopeConfigInterface as ScopeConfig;
  12. use Magento\Store\Model\ScopeInterface;
  13. /**
  14. * Catalog search auto-complete data provider.
  15. */
  16. class DataProvider implements DataProviderInterface
  17. {
  18. /**
  19. * Autocomplete limit
  20. */
  21. const CONFIG_AUTOCOMPLETE_LIMIT = 'catalog/search/autocomplete_limit';
  22. /**
  23. * Query factory
  24. *
  25. * @var QueryFactory
  26. */
  27. protected $queryFactory;
  28. /**
  29. * Autocomplete result item factory
  30. *
  31. * @var ItemFactory
  32. */
  33. protected $itemFactory;
  34. /**
  35. * Limit
  36. *
  37. * @var int
  38. */
  39. protected $limit;
  40. /**
  41. * @param QueryFactory $queryFactory
  42. * @param ItemFactory $itemFactory
  43. * @param ScopeConfig $scopeConfig
  44. */
  45. public function __construct(
  46. QueryFactory $queryFactory,
  47. ItemFactory $itemFactory,
  48. ScopeConfig $scopeConfig
  49. ) {
  50. $this->queryFactory = $queryFactory;
  51. $this->itemFactory = $itemFactory;
  52. $this->limit = (int) $scopeConfig->getValue(
  53. self::CONFIG_AUTOCOMPLETE_LIMIT,
  54. ScopeInterface::SCOPE_STORE
  55. );
  56. }
  57. /**
  58. * @inheritdoc
  59. */
  60. public function getItems()
  61. {
  62. $collection = $this->getSuggestCollection();
  63. $query = $this->queryFactory->get()->getQueryText();
  64. $result = [];
  65. foreach ($collection as $item) {
  66. $resultItem = $this->itemFactory->create([
  67. 'title' => $item->getQueryText(),
  68. 'num_results' => $item->getNumResults(),
  69. ]);
  70. if ($resultItem->getTitle() == $query) {
  71. array_unshift($result, $resultItem);
  72. } else {
  73. $result[] = $resultItem;
  74. }
  75. }
  76. return ($this->limit) ? array_splice($result, 0, $this->limit) : $result;
  77. }
  78. /**
  79. * Retrieve suggest collection for query
  80. *
  81. * @return Collection
  82. */
  83. private function getSuggestCollection()
  84. {
  85. return $this->queryFactory->get()->getSuggestCollection();
  86. }
  87. }