|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ajax\semantic\components\search; |
|
4
|
|
|
|
|
5
|
|
|
use Ajax\service\JArray; |
|
6
|
|
|
|
|
7
|
|
|
class SearchResults extends AbstractSearchResult implements ISearch { |
|
8
|
|
|
private $elements; |
|
9
|
|
|
|
|
10
|
|
|
public function __construct($objects=NULL) { |
|
11
|
|
|
$this->elements=array (); |
|
12
|
|
|
if (isset($objects)) { |
|
13
|
|
|
if (\is_array($objects)) { |
|
14
|
|
|
$this->addResults($objects); |
|
15
|
|
|
} else { |
|
16
|
|
|
$this->addResult($objects); |
|
17
|
|
|
} |
|
18
|
|
|
} |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function addResult($object) { |
|
22
|
|
|
if (\is_array($object) === false) { |
|
23
|
|
|
$object=[ "title" => $object ]; |
|
24
|
|
|
} |
|
25
|
|
|
$this->elements[]=new SearchResult($object); |
|
26
|
|
|
return $this; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function addResults($objects) { |
|
30
|
|
|
if (\is_array($objects) === false) { |
|
31
|
|
|
return $this->addResult($objects); |
|
32
|
|
|
} |
|
33
|
|
|
if (JArray::dimension($objects) === 1) { |
|
34
|
|
|
foreach ( $objects as $object ) { |
|
35
|
|
|
$this->addResult([ "title" => $object ]); |
|
36
|
|
|
} |
|
37
|
|
|
} else |
|
38
|
|
|
$this->elements=\array_merge($this->elements, $objects); |
|
39
|
|
|
return $this; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function search($query, $field="title") { |
|
43
|
|
|
$result=array (); |
|
44
|
|
|
foreach ( $this->elements as $element ) { |
|
45
|
|
|
if (\array_key_exists($field, $element)) { |
|
46
|
|
|
$value=$element[$field]; |
|
47
|
|
|
if (\stripos($value, $query) !== false) { |
|
48
|
|
|
$result[]=$element; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
if (\sizeof($result) > 0) { |
|
53
|
|
|
return $result; |
|
54
|
|
|
} |
|
55
|
|
|
return false; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function __toString() { |
|
59
|
|
|
$result="\"results\": " . \json_encode($this->elements); |
|
60
|
|
|
return $result; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function count() { |
|
64
|
|
|
return \sizeof($this->elements); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function getResponse() { |
|
68
|
|
|
return "{" . $this . "}"; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Loads results from a collection of DB objects |
|
73
|
|
|
* @param array $objects the collection of objects |
|
74
|
|
|
* @param callable $function return an array or an instance of SearchResult |
|
75
|
|
|
*/ |
|
76
|
|
|
public function fromDatabaseObjects($objects, $function) { |
|
77
|
|
|
parent::fromDatabaseObjects($objects, $function); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
protected function fromDatabaseObject($object, $function) { |
|
81
|
|
|
$this->addResult($function($object)); |
|
82
|
|
|
} |
|
83
|
|
|
} |