-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionEngine.php
More file actions
108 lines (93 loc) · 2.72 KB
/
ExpressionEngine.php
File metadata and controls
108 lines (93 loc) · 2.72 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Opifer\ExpressionEngine;
use JMS\Serializer\SerializerBuilder;
use Opifer\ExpressionEngine\Expression\Expression;
use Webmozart\Expression\Expr;
use Webmozart\Expression\Logic\AndX;
use Webmozart\Expression\Selector\Method;
class ExpressionEngine
{
/** @var string */
protected $configPath;
/**
* Constructor.
*
* @param string $configPath
*/
public function __construct($configPath = null)
{
if ($configPath) {
$this->configPath = $configPath;
} else {
$this->configPath = __DIR__.'/Resources/config';
}
}
public function serialize($collection)
{
return $this->getSerializer()->serialize($collection, 'json');
}
/**
* @param string $json
*
* @return Expression[]
*/
public function deserialize($json)
{
return $this->getSerializer()->deserialize($json, "array<Opifer\ExpressionEngine\Expression\Expression>", 'json');
}
/**
* @param Expression[] $expressions
* @param object $object
*
* @return bool
*/
public function evaluate(array $expressions, $object)
{
$expr = $this->buildExpression($expressions);
return $expr->evaluate($object);
}
/**
* @param Expression[] $collection
* @param string $type
*
* @return \Webmozart\Expression\Expression
*/
protected function buildExpression($collection, $type = AndX::class)
{
$expressions = [];
/** @var Expression $expression */
foreach ($collection as $expression) {
if (!$expression instanceof Expression) {
throw new \Exception(sprintf('Expressions must be of type %s', Expression::class));
}
if (count($expression->getChildren())) {
$expressions[] = $this->buildExpression($expression->getChildren(), $expression->getConstraint());
} else {
$expressions[] = $this->transform($expression);
}
}
return new $type($expressions);
}
/**
* Transform the expression to Webmozarts' Expression.
*
* @param Expression $expression
*
* @return \Webmozart\Expression\Expression
*/
protected function transform(Expression $expression)
{
$constraint = $expression->getConstraint();
$getter = 'get'.ucfirst($expression->getSelector());
return Expr::method($getter, new $constraint($expression->getValue()));
}
/**
* @return \JMS\Serializer\Serializer
*/
protected function getSerializer()
{
return SerializerBuilder::create()
->addMetadataDir($this->configPath)
->build();
}
}