|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
namespace Sirius\Filtration; |
|
4
|
|
|
|
|
5
|
|
|
class Utils |
|
6
|
|
|
{ |
|
7
|
15 |
|
protected static function getSelectorParts($selector) |
|
8
|
|
|
{ |
|
9
|
15 |
|
$firstOpen = strpos((string) $selector, '['); |
|
10
|
15 |
|
if ($firstOpen === false) { |
|
11
|
15 |
|
return [$selector, '']; |
|
12
|
|
|
} |
|
13
|
5 |
|
$firstClose = strpos($selector, ']'); |
|
14
|
5 |
|
$container = substr($selector, 0, $firstOpen); |
|
15
|
5 |
|
$subselector = substr($selector, $firstOpen + 1, $firstClose - $firstOpen - 1) |
|
16
|
5 |
|
. substr($selector, $firstClose + 1); |
|
17
|
5 |
|
return [$container, $subselector]; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Retrieves an element from an array via its path |
|
22
|
|
|
* Path examples: |
|
23
|
|
|
* key |
|
24
|
|
|
* key[subkey] |
|
25
|
|
|
* key[0][subkey] |
|
26
|
|
|
* |
|
27
|
|
|
* @param array $array |
|
28
|
|
|
* @param string $path |
|
29
|
|
|
* @return mixed |
|
30
|
|
|
*/ |
|
31
|
15 |
|
public static function arrayGetByPath($array, $path) |
|
32
|
|
|
{ |
|
33
|
15 |
|
list($container, $subpath) = self::getSelectorParts($path); |
|
34
|
15 |
|
if ($subpath === '') { |
|
35
|
15 |
|
return array_key_exists($container, $array) ? $array[$container] : null; |
|
36
|
|
|
} |
|
37
|
5 |
|
return array_key_exists($container, $array) ? self::arrayGetByPath($array[$container], $subpath) : null; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
14 |
|
public static function itemMatchesSelector($item, $selector) |
|
41
|
|
|
{ |
|
42
|
|
|
// the selector is a simple path identifier |
|
43
|
|
|
// NOT something like key[*][subkey] |
|
44
|
14 |
|
if (strpos($selector, '*') === false) { |
|
45
|
11 |
|
return $item === $selector; |
|
46
|
|
|
} |
|
47
|
3 |
|
$regex = '/' . str_replace('*', '[^\]]+', str_replace([ |
|
48
|
3 |
|
'[', |
|
49
|
|
|
']' |
|
50
|
|
|
], [ |
|
51
|
3 |
|
'\[', |
|
52
|
|
|
'\]' |
|
53
|
3 |
|
], $selector)) . '/'; |
|
54
|
3 |
|
return preg_match($regex, (string) $item); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|