1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* (c) Jean-François Lépine <https://twitter.com/Halleck45> |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Hal\Component\Evaluation; |
11
|
|
|
use Hal\Component\Bounds\BoundsInterface; |
12
|
|
|
use Hal\Component\Result\ResultCollection; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Evaluates rule and provides Evaluation object |
16
|
|
|
* |
17
|
|
|
* Proxy of \Hoa\Ruler\Ruler |
18
|
|
|
* |
19
|
|
|
* @author Jean-François Lépine <https://twitter.com/Halleck45> |
20
|
|
|
*/ |
21
|
|
|
class Evaluator |
22
|
|
|
{ |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var ResultCollection |
26
|
|
|
*/ |
27
|
|
|
private $collection; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var ResultCollection |
31
|
|
|
*/ |
32
|
|
|
private $aggregatedResults; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var BoundsInterface |
36
|
|
|
*/ |
37
|
|
|
private $bound; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Constructor |
41
|
|
|
* |
42
|
|
|
* @param ResultCollection $collection |
43
|
|
|
* @param ResultCollection $aggregatedResults |
44
|
|
|
* @param \Hal\Component\Bounds\BoundsInterface $bound |
45
|
|
|
*/ |
46
|
|
|
public function __construct(ResultCollection $collection, ResultCollection $aggregatedResults, BoundsInterface $bound) |
47
|
|
|
{ |
48
|
|
|
$this->aggregatedResults = $aggregatedResults; |
49
|
|
|
$this->collection = $collection; |
50
|
|
|
$this->bound = $bound; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Evaluate rule |
55
|
|
|
* |
56
|
|
|
* @param string $rule |
57
|
|
|
* @throws \LogicException |
58
|
|
|
* @return Evaluation |
59
|
|
|
*/ |
60
|
|
|
public function evaluate($rule) { |
61
|
|
|
$result = new Evaluation; |
62
|
|
|
|
63
|
|
|
if(0 == strlen($rule) ||is_null($rule)) { |
64
|
|
|
return $result; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$bounds = $this->bound->calculate($this->collection); |
68
|
|
|
$ruler = new \Hoa\Ruler\Ruler(); |
69
|
|
|
$context = new \Hoa\Ruler\Context(); |
70
|
|
|
|
71
|
|
|
// general |
72
|
|
|
foreach($bounds->asArray() as $category => $values) { |
73
|
|
|
$context[$category] = (object) $values; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
// by package |
77
|
|
|
foreach($this->aggregatedResults as $aggregate) { |
78
|
|
|
$array = $aggregate->asArray(); |
79
|
|
|
$c = array(); |
80
|
|
|
foreach($array as $k => $v) { |
81
|
|
|
if(is_array($v)) { |
82
|
|
|
$v = (object) $v; |
83
|
|
|
} |
84
|
|
|
$c[$k] = $v; |
85
|
|
|
} |
86
|
|
|
$context[$aggregate->getName()] = (object) $c; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
|
90
|
|
|
try { |
91
|
|
|
$result->setValid(true === $ruler->assert($rule, $context)); |
92
|
|
|
} catch(\Hoa\Ruler\Exception\Asserter $e) { |
93
|
|
|
throw new \LogicException(sprintf('Cannot evaluate rule : %s', $e->getMessage())); |
94
|
|
|
} |
95
|
|
|
return $result; |
96
|
|
|
} |
97
|
|
|
} |