1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JamesMoss\Flywheel; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Query |
7
|
|
|
* |
8
|
|
|
* Builds an executes a query whichs searches and sorts documents from a |
9
|
|
|
* repository. |
10
|
|
|
*/ |
11
|
|
|
class Predicate |
12
|
|
|
{ |
13
|
|
|
const LOGICAL_AND = 'and'; |
14
|
|
|
const LOGICAL_OR = 'or'; |
15
|
|
|
|
16
|
|
|
protected $predicates = array(); |
17
|
|
|
protected $operators = array( |
18
|
|
|
'>', '>=', '<', '<=', '==', '===', '!=', '!==', |
19
|
|
|
); |
20
|
|
|
|
21
|
17 |
|
public function getAll() |
22
|
|
|
{ |
23
|
17 |
|
return $this->predicates; |
24
|
|
|
} |
25
|
|
|
|
26
|
18 |
|
public function where($field, $operator = null, $value = null) |
27
|
|
|
{ |
28
|
18 |
|
return $this->andWhere($field, $operator, $value); |
29
|
|
|
} |
30
|
|
|
|
31
|
18 |
|
public function andWhere($field, $operator = null, $value = null) |
32
|
|
|
{ |
33
|
18 |
|
$this->addPredicate(self::LOGICAL_AND, $field, $operator, $value); |
34
|
|
|
|
35
|
15 |
|
return $this; |
36
|
|
|
} |
37
|
|
|
|
38
|
5 |
|
public function orWhere($field, $operator = null, $value = null) |
39
|
|
|
{ |
40
|
5 |
|
$this->addPredicate(self::LOGICAL_OR, $field, $operator, $value); |
41
|
|
|
|
42
|
5 |
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
18 |
|
protected function addPredicate($type, $field, $operator = null, $value = null) |
46
|
|
|
{ |
47
|
18 |
|
if (!$this->predicates) { |
|
|
|
|
48
|
18 |
|
$type = false; |
49
|
18 |
|
} |
50
|
|
|
|
51
|
18 |
|
if ($field instanceof \Closure) { |
52
|
2 |
|
$sub = new self(); |
53
|
2 |
|
call_user_func($field, $sub); |
54
|
|
|
|
55
|
2 |
|
$this->predicates[] = array($type, $sub->getAll()); |
56
|
|
|
|
57
|
2 |
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
18 |
|
$field = trim($field); |
61
|
|
|
|
62
|
18 |
|
if ($field == '') { |
63
|
2 |
|
throw new \InvalidArgumentException('Field name cannot be empty.'); |
64
|
|
|
} |
65
|
|
|
|
66
|
16 |
|
if (!in_array($operator, $this->operators)) { |
67
|
1 |
|
throw new \InvalidArgumentException('Unknown operator `'.$operator.'`.'); |
68
|
|
|
} |
69
|
|
|
|
70
|
15 |
|
$this->predicates[] = array($type, $field, $operator, $value); |
71
|
|
|
|
72
|
15 |
|
return $this; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.