|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace allejo\stakx\Twig; |
|
4
|
|
|
|
|
5
|
|
|
use allejo\stakx\Object\ContentItem; |
|
6
|
|
|
use Twig_Error_Syntax; |
|
7
|
|
|
|
|
8
|
|
|
class WhereFilter |
|
9
|
|
|
{ |
|
10
|
20 |
|
public function __invoke ($array, $key, $comparison, $value) |
|
11
|
|
|
{ |
|
12
|
20 |
|
$results = array(); |
|
13
|
20 |
|
$this->search_r($array, $key, $comparison, $value, $results); |
|
14
|
|
|
|
|
15
|
19 |
|
return $results; |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
1 |
|
public static function get () |
|
19
|
|
|
{ |
|
20
|
1 |
|
return new \Twig_SimpleFilter('where', new self()); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
20 |
|
private function search_r ($array, $key, $comparison, $value, &$results) |
|
|
|
|
|
|
24
|
|
|
{ |
|
25
|
20 |
|
if (!is_array($array) && !($array instanceof ContentItem)) |
|
26
|
20 |
|
{ |
|
27
|
19 |
|
return; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
20 |
|
if ($this->compare($array, $key, $comparison, $value)) |
|
31
|
20 |
|
{ |
|
32
|
14 |
|
$results[] = $array; |
|
33
|
14 |
|
} |
|
34
|
|
|
|
|
35
|
20 |
|
foreach ($array as $subarray) |
|
|
|
|
|
|
36
|
|
|
{ |
|
37
|
20 |
|
$this->search_r($subarray, $key, $comparison, $value, $results); |
|
38
|
19 |
|
} |
|
39
|
19 |
|
} |
|
40
|
|
|
|
|
41
|
20 |
|
private function compare ($array, $key, $comparison, $value) |
|
42
|
|
|
{ |
|
43
|
20 |
|
$fm = false; |
|
44
|
|
|
|
|
45
|
20 |
|
if ($array instanceof ContentItem) |
|
46
|
20 |
|
{ |
|
47
|
|
|
$array = $array->getFrontMatter(); |
|
48
|
|
|
$fm = true; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
20 |
|
if (!isset($array[$key])) |
|
52
|
20 |
|
{ |
|
53
|
20 |
|
return ($fm && $comparison === "==" && $value === null); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
switch ($comparison) |
|
57
|
|
|
{ |
|
58
|
19 |
|
case "==": return ($array[$key] === $value); |
|
|
|
|
|
|
59
|
14 |
|
case "!=": return ($array[$key] !== $value); |
|
|
|
|
|
|
60
|
11 |
|
case ">" : return ($array[$key] > $value); |
|
|
|
|
|
|
61
|
9 |
|
case ">=": return ($array[$key] >= $value); |
|
|
|
|
|
|
62
|
7 |
|
case "<" : return ($array[$key] < $value); |
|
|
|
|
|
|
63
|
5 |
|
case "<=": return ($array[$key] <= $value); |
|
|
|
|
|
|
64
|
3 |
|
case "~=": return ($this->contains($array[$key], $value)); |
|
|
|
|
|
|
65
|
|
|
|
|
66
|
1 |
|
default: |
|
67
|
1 |
|
throw new Twig_Error_Syntax("Invalid where comparison ({$comparison})"); |
|
68
|
1 |
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
2 |
|
private function contains ($haystack, $needle) |
|
72
|
|
|
{ |
|
73
|
2 |
|
return ((is_array($haystack) && in_array($needle, $haystack)) || |
|
74
|
2 |
|
(is_string($haystack) && strpos($haystack, $needle) !== false)); |
|
75
|
|
|
} |
|
76
|
|
|
} |
This check looks for method names that are not written in camelCase.
In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes
databaseConnectionSeeker.