-
Notifications
You must be signed in to change notification settings - Fork 22
/
InvariantCheckerAspect.php
77 lines (67 loc) · 2.15 KB
/
InvariantCheckerAspect.php
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
<?php
/**
* PHP Deal framework
*
* @copyright Copyright 2014, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpDeal\Aspect;
use Doctrine\Common\Annotations\Reader;
use Go\Aop\Aspect;
use Go\Aop\Intercept\MethodInvocation;
use PhpDeal\Annotation\Invariant;
use PhpDeal\Contract\Fetcher\Parent\InvariantFetcher;
use PhpDeal\Exception\ContractViolation;
use Go\Lang\Annotation\Around;
use ReflectionClass;
class InvariantCheckerAspect extends AbstractContractAspect implements Aspect
{
/**
* @var InvariantFetcher
*/
private $invariantFetcher;
public function __construct(Reader $reader)
{
parent::__construct($reader);
$this->invariantFetcher = new InvariantFetcher([Invariant::class], $reader);
}
/**
* Verifies invariants for contract class
*
* @Around("@within(PhpDeal\Annotation\Invariant) && execution(public **->*(*))")
* @param MethodInvocation $invocation
*
* @throws ContractViolation
* @return mixed
*/
public function invariantContract(MethodInvocation $invocation)
{
$object = $invocation->getThis();
$args = $this->fetchMethodArguments($invocation);
$class = $invocation->getMethod()->getDeclaringClass();
if ($class->isCloneable()) {
$args['__old'] = clone $object;
}
$result = $invocation->proceed();
$args['__result'] = $result;
$allContracts = $this->fetchAllContracts($class);
$this->ensureContracts($invocation, $allContracts, $object, $class->name, $args);
return $result;
}
/**
* @param ReflectionClass $class
* @return array
*/
private function fetchAllContracts(ReflectionClass $class)
{
$allContracts = $this->invariantFetcher->getConditions($class);
foreach ($this->reader->getClassAnnotations($class) as $annotation) {
if ($annotation instanceof Invariant) {
$allContracts[] = $annotation;
}
}
return array_unique($allContracts);
}
}