/
GambitManager.php
114 lines (98 loc) · 2.41 KB
/
GambitManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Search;
use LogicException;
/**
* @internal
*/
class GambitManager
{
/**
* @var array
*/
protected $gambits = [];
/**
* @var GambitInterface
*/
protected $fulltextGambit;
/**
* @param GambitInterface $gambit
*/
public function __construct(GambitInterface $fulltextGambit)
{
$this->fulltextGambit = $fulltextGambit;
}
/**
* Add a gambit.
*
* @param GambitInterface $gambit
*/
public function add(GambitInterface $gambit)
{
$this->gambits[] = $gambit;
}
/**
* Apply gambits to a search, given a search query.
*
* @param SearchState $search
* @param string $query
*/
public function apply(SearchState $search, $query)
{
$query = $this->applyGambits($search, $query);
if ($query) {
$this->applyFulltext($search, $query);
}
}
/**
* Explode a search query into an array of bits.
*
* @param string $query
* @return array
*/
protected function explode($query)
{
return str_getcsv($query, ' ');
}
/**
* @param SearchState $search
* @param string $query
* @return string
*/
protected function applyGambits(SearchState $search, $query)
{
$bits = $this->explode($query);
if (! $bits) {
return '';
}
foreach ($bits as $k => $bit) {
foreach ($this->gambits as $gambit) {
if (! $gambit instanceof GambitInterface) {
throw new LogicException(
'Gambit '.get_class($gambit).' does not implement '.GambitInterface::class
);
}
if ($gambit->apply($search, $bit)) {
$search->addActiveGambit($gambit);
unset($bits[$k]);
break;
}
}
}
return implode(' ', $bits);
}
/**
* @param SearchState $search
* @param string $query
*/
protected function applyFulltext(SearchState $search, $query)
{
$search->addActiveGambit($this->fulltextGambit);
$this->fulltextGambit->apply($search, $query);
}
}