Searchable   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 275
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 91.57%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 9
dl 0
loc 275
ccs 76
cts 83
cp 0.9157
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 10 2
A search() 0 16 2
A deleteAllFromSearch() 0 10 2
A queueDeleteFromSearch() 0 18 4
A queueMakeSearchable() 0 18 4
A upsert() 0 21 4
A delete() 0 16 3
A initIndex() 0 11 2
A createTNTSearch() 0 17 1
1
<?php
2
/**
3
 * @link https://github.com/vuongxuongminh/yii2-searchable
4
 * @copyright Copyright (c) 2019 Vuong Xuong Minh
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace vxm\searchable;
9
10
use Yii;
11
12
use yii\base\Component;
13
use yii\db\Connection;
14
use yii\di\Instance;
15
use yii\queue\Queue;
16
17
use vxm\searchable\queue\DeleteSearchable;
18
use vxm\searchable\queue\MakeSearchable;
19
20
/**
21
 * Class TNTSearch support full-text search via tnt search.
22
 *
23
 * @author Vuong Minh <[email protected]>
24
 * @since 1.0.0
25
 */
26
class Searchable extends Component
27
{
28
    /**
29
     * Search data with boolean mode.
30
     */
31
    const BOOLEAN_SEARCH = 'boolean';
32
33
    /**
34
     * Search data with fuzzy mode.
35
     */
36
    const FUZZY_SEARCH = 'fuzzy';
37
38
    /**
39
     * @var string default search mode for [[search()]] if `$mode` param not set.
40
     */
41
    public $defaultSearchMode = self::FUZZY_SEARCH;
42
43
    /**
44
     * @var string the TNTSearch class.
45
     */
46
    public $tntSearchClass = TNTSearch::class;
47
48
    /**
49
     * @var bool default as you type search config.
50
     */
51
    public $asYouType = false;
52
53
    /**
54
     * @var bool default fuzziness search config.
55
     */
56
    public $fuzziness = false;
57
58
    /**
59
     * @var int default fuzzy prefix length config.
60
     */
61
    public $fuzzyPrefixLength = 2;
62
63
    /**
64
     * @var int default fuzzy max expansions config.
65
     */
66
    public $fuzzyMaxExpansions = 50;
67
68
    /**
69
     * @var int default fuzzy distance config.
70
     */
71
    public $fuzzyDistance = 2;
72
73
    /**
74
     * @var string default storage path of index data.
75
     */
76
    public $storagePath = '@runtime/vxm/searchable';
77
78
    /**
79
     * @var Queue|null use for support make or delete index data via worker.
80
     */
81
    public $queue;
82
83
    /**
84
     * @inheritDoc
85
     * @throws \yii\base\InvalidConfigException
86
     */
87 13
    public function init()
88
    {
89 13
        $this->storagePath = Yii::getAlias($this->storagePath);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->storagePath) can also be of type boolean. However, the property $storagePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
90
91 13
        if ($this->queue !== null) {
92
            $this->queue = Instance::ensure($this->queue, Queue::class);
93
        }
94
95 13
        parent::init();
96 13
    }
97
98
    /**
99
     * Search by model class via given query string.
100
     *
101
     * @param string $modelClass need to search.
102
     * @param string $query apply to search.
103
     * @param string $mode boolean or fuzzy search mode.
104
     * @param array $config of [[\vxm\searchable\TNTSearch]].
105
     * @param int $limit of values search.
106
     * @return array search results.
107
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
108
     * @throws \yii\base\InvalidConfigException
109
     */
110 8
    public function search(string $modelClass, string $query, ?string $mode = null, array $config = [], int $limit = 100): array
111
    {
112
        /** @var \yii\db\ActiveRecord $modelClass */
113 8
        $this->initIndex($modelClass, $config);
0 ignored issues
show
Documentation introduced by
$modelClass is of type object<yii\db\ActiveRecord>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
114 8
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
115 8
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
116 8
        $mode = $mode ?? $this->defaultSearchMode;
117
118 8
        if ($mode === self::BOOLEAN_SEARCH) {
119
120 1
            return $tnt->searchBoolean($query, $limit);
121
        } else {
122
123 8
            return $tnt->search($query, $limit);
124
        }
125
    }
126
127
    /**
128
     * Delete all instances of the model class from the search index.
129
     *
130
     * @param string $modelClass need to delete all instances.
131
     * @param array $config of [[\vxm\searchable\TNTSearch]].
132
     * @throws \yii\base\InvalidConfigException
133
     */
134 5
    public function deleteAllFromSearch(string $modelClass, array $config = []): void
135
    {
136
        /** @var \yii\db\ActiveRecord $modelClass */
137 5
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
138 5
        $pathToIndex = $tnt->config['storage'] . "/{$modelClass::searchableIndex()}.index";
139
140 5
        if (file_exists($pathToIndex)) {
141 3
            unlink($pathToIndex);
142
        }
143 5
    }
144
145
    /**
146
     * Dispatch the job to make the given models unsearchable.
147
     *
148
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue.
149
     * @param array $config of [[\vxm\searchable\TNTSearch]].
150
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
151
     * @throws \yii\base\InvalidConfigException
152
     */
153 3
    public function queueDeleteFromSearch($models, array $config = []): void
154
    {
155 3
        $models = is_array($models) ? $models : [$models];
156
157 3
        if (empty($models)) {
158
159
            return;
160
        }
161
162 3
        if ($this->queue === null) {
163
164 3
            $this->delete($models, $config);
165
        } else {
166
167
            $job = new DeleteSearchable($models);
168
            $this->queue->push($job);
169
        }
170 3
    }
171
172
    /**
173
     * Dispatch the job to make the given models searchable.
174
     *
175
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue job.
176
     * @param array $config of [[\vxm\searchable\TNTSearch]].
177
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
178
     * @throws \yii\base\InvalidConfigException
179
     */
180 10
    public function queueMakeSearchable($models, array $config = []): void
181
    {
182 10
        $models = is_array($models) ? $models : [$models];
183
184 10
        if (empty($models)) {
185
186
            return;
187
        }
188
189 10
        if ($this->queue === null) {
190
191 10
            $this->upsert($models, $config);
192
        } else {
193
194
            $job = new MakeSearchable($models);
195
            $this->queue->push($job);
196
        }
197 10
    }
198
199
    /**
200
     * Update or insert models to search engine.
201
     *
202
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models dispatch to queue.
203
     * @param array $config of [[\vxm\searchable\TNTSearch]].
204
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
205
     * @throws \yii\base\InvalidConfigException
206
     */
207 10
    public function upsert($models, array $config = []): void
208
    {
209 10
        $models = is_array($models) ? $models : [$models];
210
        /** @var \yii\db\ActiveRecord $modelClass */
211 10
        $modelClass = get_class(current($models));
212 10
        $this->initIndex($modelClass, $config);
0 ignored issues
show
Documentation introduced by
$modelClass is of type object<yii\db\ActiveRecord>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
213 10
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
214 10
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
215 10
        $index = $tnt->getIndex();
216 10
        $index->setPrimaryKey($modelClass::searchableKey());
217 10
        $index->indexBeginTransaction();
218
219 10
        foreach ($models as $model) {
220
221 10
            if ($data = $model->toSearchableArray()) {
222 10
                $index->update($model->getSearchableKey(), $data);
223
            }
224
        }
225
226 10
        $index->indexEndTransaction();
227 10
    }
228
229
    /**
230
     * Delete models from search engine.
231
     *
232
     * @param \yii\db\ActiveRecord|\yii\db\ActiveRecord[]|static|static[] $models need to delete.
233
     * @param array $config of [[\vxm\searchable\TNTSearch]].
234
     * @throws \TeamTNT\TNTSearch\Exceptions\IndexNotFoundException
235
     * @throws \yii\base\InvalidConfigException
236
     */
237 3
    public function delete($models, array $config = []): void
238
    {
239 3
        $models = is_array($models) ? $models : [$models];
240
        /** @var \yii\db\ActiveRecord $modelClass */
241 3
        $modelClass = get_class(current($models));
242 3
        $this->initIndex($modelClass, $config);
0 ignored issues
show
Documentation introduced by
$modelClass is of type object<yii\db\ActiveRecord>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
243 3
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
244 3
        $tnt->selectIndex("{$modelClass::searchableIndex()}.index");
245 3
        $index = $tnt->getIndex();
246 3
        $index->setPrimaryKey($modelClass::searchableKey());
247
248 3
        foreach ($models as $model) {
249
            /** @var \yii\db\ActiveRecord $model */
250 3
            $index->delete($model->getSearchableKey());
251
        }
252 3
    }
253
254
    /**
255
     * Init index data of model class.
256
     *
257
     * @param string $modelClass to init index data.
258
     * @param array $config of [[\vxm\searchable\TNTSearch]].
259
     * @throws \yii\base\InvalidConfigException
260
     */
261 12
    public function initIndex(string $modelClass, array $config = []): void
262
    {
263
        /** @var \yii\db\ActiveRecord $modelClass */
264 12
        $index = $modelClass::searchableIndex() . '.index';
265 12
        $tnt = $this->createTNTSearch($modelClass::getDb(), $config);
266
267 12
        if (!file_exists($tnt->config['storage'] . "/{$index}")) {
268 4
            $indexer = $tnt->createIndex($index);
269 4
            $indexer->setPrimaryKey($modelClass::searchableKey());
270
        }
271 12
    }
272
273
    /**
274
     * Create tnt search object.
275
     *
276
     * @param Connection|null $db use to get database info.
277
     * @param array $config of [[\vxm\searchable\TNTSearch]].
278
     * @return object|TNTSearch
279
     * @throws \yii\base\InvalidConfigException
280
     */
281 12
    public function createTNTSearch(?Connection $db = null, array $config = []): TNTSearch
282
    {
283 12
        $db = $db ?? Yii::$app->getDb();
284 12
        $dbh = $db->getMasterPdo();
285 12
        $tnt = Yii::createObject([
286 12
            'class' => $this->tntSearchClass,
287 12
            'asYouType' => $config['asYouType'] ?? $this->asYouType,
288 12
            'fuzziness' => $config['fuzziness'] ?? $this->fuzziness,
289 12
            'fuzzy_distance' => $config['fuzzy_distance'] ?? $config['fuzzyDistance'] ?? $this->fuzzyDistance,
290 12
            'fuzzy_prefix_length' => $config['fuzzy_prefix_length'] ?? $config['fuzzyPrefixLength'] ?? $this->fuzzyPrefixLength,
291 12
            'fuzzy_max_expansions' => $config['fuzzy_max_expansions'] ?? $config['fuzzyMaxExpansions'] ?? $this->fuzzyMaxExpansions
292
        ]);
293 12
        $tnt->loadConfig(['storage' => $this->storagePath]);
294 12
        $tnt->setDatabaseHandle($dbh);
295
296 12
        return $tnt;
297
    }
298
299
300
}
301