Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
QueryFactory.php
Go to the documentation of this file.
1 <?php
6 namespace Magento\Search\Model;
7 
12 use Magento\Framework\Stdlib\StringUtils as StdlibString;
13 
19 {
23  const QUERY_VAR_NAME = 'q';
24 
28  private $request;
29 
33  private $query;
34 
38  private $objectManager;
39 
43  private $string;
44 
48  private $scopeConfig;
49 
53  private $queryHelper;
54 
61  public function __construct(
62  Context $context,
63  ObjectManagerInterface $objectManager,
64  StdlibString $string,
65  Data $queryHelper = null
66  ) {
67  $this->request = $context->getRequest();
68  $this->objectManager = $objectManager;
69  $this->string = $string;
70  $this->scopeConfig = $context->getScopeConfig();
71  $this->queryHelper = $queryHelper === null ? $this->objectManager->get(Data::class) : $queryHelper;
72  }
73 
77  public function get()
78  {
79  if (!$this->query) {
80  $maxQueryLength = $this->queryHelper->getMaxQueryLength();
81  $minQueryLength = $this->queryHelper->getMinQueryLength();
82  $rawQueryText = $this->getRawQueryText();
83  $preparedQueryText = $this->getPreparedQueryText($rawQueryText, $maxQueryLength);
84  $query = $this->create()->loadByQueryText($preparedQueryText);
85  if (!$query->getId()) {
86  $query->setQueryText($preparedQueryText);
87  }
88  $query->setIsQueryTextExceeded($this->isQueryTooLong($rawQueryText, $maxQueryLength));
89  $query->setIsQueryTextShort($this->isQueryTooShort($rawQueryText, $minQueryLength));
90  $this->query = $query;
91  }
92  return $this->query;
93  }
94 
101  public function create(array $data = [])
102  {
103  return $this->objectManager->create(Query::class, $data);
104  }
105 
111  private function getRawQueryText()
112  {
113  $queryText = $this->request->getParam(self::QUERY_VAR_NAME);
114  return ($queryText === null || is_array($queryText))
115  ? ''
116  : $this->string->cleanString(trim($queryText));
117  }
118 
124  private function getPreparedQueryText($queryText, $maxQueryLength)
125  {
126  if ($this->isQueryTooLong($queryText, $maxQueryLength)) {
127  $queryText = $this->string->substr($queryText, 0, $maxQueryLength);
128  }
129  return $queryText;
130  }
131 
137  private function isQueryTooLong($queryText, $maxQueryLength)
138  {
139  return ($maxQueryLength !== '' && $this->string->strlen($queryText) > $maxQueryLength);
140  }
141 
147  private function isQueryTooShort($queryText, $minQueryLength)
148  {
149  return ($this->string->strlen($queryText) < $minQueryLength);
150  }
151 }
__construct(Context $context, ObjectManagerInterface $objectManager, StdlibString $string, Data $queryHelper=null)
$objectManager
Definition: bootstrap.php:17
$maxQueryLength
Definition: form.phtml:17