Completed
Push — master ( 751bb4...735cac )
by Jean-Christophe
04:44
created

SearchResults   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 58
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A addResult() 0 4 1
A addResults() 0 9 3
B search() 0 15 5
A __toString() 0 4 1
A count() 0 3 1
A getStandard() 0 3 1
1
<?php
2
3
namespace Ajax\semantic\components\search;
4
5
use Ajax\service\JArray;
6
7
class SearchResults {
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
		$this->elements[]=$object;
23
		return $this;
24
	}
25
26
	public function addResults($objects) {
27
		if (JArray::dimension($objects) === 1) {
28
			foreach ( $objects as $object ) {
29
				$this->addResult([ "title" => $object ]);
30
			}
31
		} else
32
			$this->elements=\array_merge($this->elements, $objects);
33
		return $this;
34
	}
35
36
	public function search($query, $field="title") {
37
		$result=array ();
38
		foreach ( $this->elements as $element ) {
39
			if (\array_key_exists($field, $element)) {
40
				$value=$element[$field];
41
				if (\stripos($value, $query) !== false) {
42
					$result[]=$element;
43
				}
44
			}
45
		}
46
		if (\sizeof($result) > 0) {
47
			return $result;
48
		}
49
		return false;
50
	}
51
52
	public function __toString() {
53
		$result="\"results\": " . \json_encode($this->elements);
54
		return $result;
55
	}
56
57
	public function count() {
58
		return \sizeof($this->elements);
59
	}
60
61
	public function getStandard() {
62
		return "{" . $this . "}";
63
	}
64
}