Completed
Push — master ( 641d44...69e9f4 )
by Jean-Christophe
03:56
created

SearchResults::_search()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 20
rs 8.2222
cc 7
eloc 14
nc 12
nop 2
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 ($object instanceof SearchResult) {
23
			$this->elements[]=$object;
24
			return $this;
25
		}
26
		if (\is_array($object) === false) {
27
			$object=[ "title" => $object ];
28
		}
29
		$this->elements[]=new SearchResult($object);
30
		return $this;
31
	}
32
33
	public function addResults($objects) {
34
		if (\is_array($objects) === false) {
35
			return $this->addResult($objects);
36
		}
37
		if (JArray::dimension($objects) === 1) {
38
			foreach ( $objects as $object ) {
39
				$this->addResult([ "title" => $object ]);
40
			}
41
		} else
42
			$this->elements=\array_merge($this->elements, $objects);
43
		return $this;
44
	}
45
46
	public function _search($query, $field="title") {
47
		$result=array ();
48
		foreach ( $this->elements as $element ) {
49
			if ($element instanceof SearchResult) {
50
				if ($element->search($query, $field) !== false)
51
					$result[]=$element->asArray();
52
			} else {
53
				if (\array_key_exists($field, $element)) {
54
					$value=$element[$field];
55
					if (\stripos($value, $query) !== false) {
56
						$result[]=$element;
57
					}
58
				}
59
			}
60
		}
61
		if (\sizeof($result) > 0) {
62
			return $result;
63
		}
64
		return false;
65
	}
66
67
	public function search($query, $field="title") {
68
		$result=$this->_search($query, $field);
69
		if ($result === false)
70
			$result=NULL;
71
		return new SearchResults($result);
72
	}
73
74
	public function __toString() {
75
		$result="\"results\": " . \json_encode($this->elements);
76
		return $result;
77
	}
78
79
	public function count() {
80
		return \sizeof($this->elements);
81
	}
82
83
	public function getResponse() {
84
		return "{" . $this . "}";
85
	}
86
87
	/**
88
	 * Loads results from a collection of DB objects
89
	 * @param array $objects the collection of objects
90
	 * @param callable $function return an array or an instance of SearchResult
91
	 */
92
	public function fromDatabaseObjects($objects, $function) {
93
		parent::fromDatabaseObjects($objects, $function);
94
	}
95
96
	protected function fromDatabaseObject($object, $function) {
97
		$this->addResult($function($object));
98
	}
99
}