-
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathQueryResultFilter.php
More file actions
53 lines (42 loc) · 1.49 KB
/
QueryResultFilter.php
File metadata and controls
53 lines (42 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/**
* JSONPath implementation for PHP.
*
* @license https://github.com/SoftCreatR/JSONPath/blob/main/LICENSE MIT License
*/
declare(strict_types=1);
namespace Flow\JSONPath\Filters;
use Flow\JSONPath\AccessHelper;
use Flow\JSONPath\JSONPathException;
class QueryResultFilter extends AbstractFilter
{
/**
* @throws JSONPathException
* @inheritDoc
*/
public function filter(array|object $collection): array
{
if (!\preg_match('/@\.(?<key>\w+)\s*(?<operator>[-+*\/])\s*(?<numeric>\d+)/', $this->token->value, $matches)) {
throw new JSONPathException('Unsupported operator in expression');
}
$matchKey = $matches['key'];
if (AccessHelper::keyExists($collection, $matchKey, $this->magicIsAllowed)) {
$value = AccessHelper::getValue($collection, $matchKey, $this->magicIsAllowed);
} elseif ($matches['key'] === 'length') {
$value = \count($collection);
} else {
return [];
}
$resultKey = match ($matches['operator']) {
'+' => $value + $matches['numeric'],
'*' => $value * $matches['numeric'],
'-' => $value - $matches['numeric'],
'/' => $value / $matches['numeric'],
};
$result = [];
if (AccessHelper::keyExists($collection, $resultKey, $this->magicIsAllowed)) {
$result[] = AccessHelper::getValue($collection, $resultKey, $this->magicIsAllowed);
}
return $result;
}
}