/
Index.php
119 lines (98 loc) · 2.92 KB
/
Index.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
115
116
117
118
119
<?php
namespace Statamic\Search\Comb;
use Statamic\Facades\File;
use Statamic\Search\Comb\Exceptions\NoQuery;
use Statamic\Search\Comb\Exceptions\NoResultsFound;
use Statamic\Search\Comb\Exceptions\NotEnoughCharacters;
use Statamic\Search\Documents;
use Statamic\Search\Index as BaseIndex;
use Statamic\Search\IndexNotFoundException;
class Index extends BaseIndex
{
public function search($query)
{
return (new Query($this))->query($query);
}
public function lookup($query)
{
$data = $this->data()->map(function ($item, $reference) {
return $item + ['reference' => $reference];
})->values()->toArray();
$comb = new Comb($data, $this->settings());
try {
$results = $comb->lookUp($query)['data'];
} catch (NoResultsFound|NotEnoughCharacters|NoQuery $e) {
return collect();
}
return collect($results)->map(function ($result) {
$data = $result['data'];
$data['search_score'] = $result['score'];
return array_except($data, '_category');
});
}
protected function data()
{
return collect(json_decode($this->raw(), true));
}
protected function settings()
{
return array_merge([
'match_weights' => null,
'min_characters' => null,
'min_word_characters' => null,
'score_threshold' => null,
'property_weights' => null,
'query_mode' => null,
'use_stemming' => false,
'use_alternates' => false,
'include_full_query' => null,
'enable_too_many_results' => null,
'sort_by_score' => null,
'exclude_properties' => null,
'stop_words' => ['the', 'a', 'an'],
'include_properties' => $this->config['fields'] ?? ['title'],
], $this->config);
}
public function raw()
{
if (! $this->exists()) {
throw new IndexNotFoundException;
}
return File::get($this->path());
}
public function exists()
{
return File::exists($this->path());
}
public function path()
{
return sprintf('%s/%s.json', $this->config['path'], $this->name);
}
public function delete($document)
{
try {
$data = $this->data();
} catch (IndexNotFoundException $e) {
return;
}
$data->forget($document->reference());
$this->save($data);
}
protected function insertDocuments(Documents $documents)
{
try {
$data = $this->data();
} catch (IndexNotFoundException $e) {
$data = collect();
}
$this->save($documents->union($data));
}
public function deleteIndex()
{
File::delete($this->path());
}
protected function save($documents)
{
File::put($this->path(), $documents->toJson());
}
}