Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SynonymAnalyzer.php
Go to the documentation of this file.
1 <?php
7 declare(strict_types=1);
8 namespace Magento\Search\Model;
9 
11 
16 {
20  protected $synReaderModel;
21 
27  public function __construct(SynonymReader $synReader)
28  {
29  $this->synReaderModel = $synReader;
30  }
31 
49  public function getSynonymsForPhrase($phrase)
50  {
51  $result = [];
52 
53  if (empty(trim($phrase))) {
54  return $result;
55  }
56 
57  $synonymGroups = $this->getSynonymGroupsByPhrase($phrase);
58 
59  // Replace multiple spaces in a row with the only one space
60  $phrase = preg_replace("/ {2,}/", " ", $phrase);
61 
62  // Go through every returned record looking for presence of the actual phrase. If there were no matching
63  // records found in DB then create a new entry for it in the returned array
64  $words = explode(' ', $phrase);
65 
66  foreach ($words as $offset => $word) {
67  $synonyms = [$word];
68 
69  if ($synonymGroups) {
70  $pattern = $this->getSearchPattern(\array_slice($words, $offset));
71  $position = $this->findInArray($pattern, $synonymGroups);
72  if ($position !== null) {
73  $synonyms = explode(',', $synonymGroups[$position]);
74  }
75  }
76 
77  $result[] = $synonyms;
78  }
79 
80  return $result;
81  }
82 
92  private function findInArray(string $pattern, array $synonymGroupsToExamine)
93  {
94  $position = 0;
95  foreach ($synonymGroupsToExamine as $synonymGroup) {
96  $matchingResultCode = preg_match($pattern, $synonymGroup);
97  if ($matchingResultCode === 1) {
98  return $position;
99  }
100  $position++;
101  }
102 
103  return null;
104  }
105 
135  private function getSearchPattern(array $words): string
136  {
137  $patterns = [];
138  for ($lastItem = count($words); $lastItem > 0; $lastItem--) {
139  $phrase = implode("\s+", \array_slice($words, 0, $lastItem));
140  $patterns[] = '^' . $phrase . ',';
141  $patterns[] = ',' . $phrase . ',';
142  $patterns[] = ',' . $phrase . '$';
143  }
144 
145  $pattern = '/' . implode('|', $patterns) . '/i';
146  return $pattern;
147  }
148 
158  private function getSynonymGroupsByPhrase(string $phrase): array
159  {
160  $result = [];
161 
163  $synonymGroups = $this->synReaderModel->loadByPhrase($phrase)->getData();
164  foreach ($synonymGroups as $row) {
165  $result[] = $row['synonyms'];
166  }
167  return $result;
168  }
169 }
$pattern
Definition: website.php:22
__construct(SynonymReader $synReader)