-
Notifications
You must be signed in to change notification settings - Fork 2
/
fuzzy-search.php
57 lines (47 loc) · 1.42 KB
/
fuzzy-search.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
<?php
/**
* Kirby Fuzzy Search Plugin
*
* @version 1.0.0-beta
* @author Pedro Borges <oi@pedroborg.es>
* @copyright Pedro Borges <oi@pedroborg.es>
* @link https://github.com/pedroborges/kirby-fuzzy-search
* @license MIT
*/
// Load Composer dependencies
require __DIR__.DS.'vendor'.DS.'autoload.php';
use PedroBorges\FuzzySearch\FuzzySearch;
if (! function_exists('fuzzySearch')) {
/**
* Perform fuzzy-search on an array of data.
*
* @param mixed $data
* @param string $query
* @param array $fields
* @return array
*/
function fuzzySearch($data, string $query, $fields = []) {
$fuzzy = new FuzzySearch($data, $fields);
return $fuzzy->search($query);
}
}
$kirby->set('field::method', 'fuzzySearch', function(Field $field, string $query, $fields = []) {
$results = fuzzySearch($field, $query, $fields);
// Return result as Field to allow
// for chaining of field methods
return new Field(
$field->page(),
$field->key(),
Yaml::encode($results)
);
});
$kirby->set('pages::method', 'fuzzySearch', function(Pages $pages, string $query, $fields = []) {
$results = fuzzySearch($pages, $query, $fields);
// Retrieve pages IDs from results
// to rebuild Pages collection
$pageIDs = [];
foreach ($results as $page) {
$pageIDs[] = $page['id'];
}
return $pages->filterBy('id', 'in', $pageIDs);
});