Completed
Push — master ( bde278...56c4be )
by Alexander
9s
created

PostconditionContract::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * PHP Deal framework
4
 *
5
 * @copyright Copyright 2014, Lisachenko Alexander <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace PhpDeal\Contract;
12
13
use Doctrine\Common\Annotations\Reader;
14
use Go\Aop\Intercept\MethodInvocation;
15
use PhpDeal\Contract\Fetcher\ParentClass\MethodConditionFetcher;
16
use PhpDeal\Exception\ContractViolation;
17
use PhpDeal\Annotation\Ensure;
18
19
class PostconditionContract extends Contract
20
{
21
    /**
22
     * @var MethodConditionFetcher
23
     */
24
    private $methodConditionFetcher;
25
26
    public function __construct(Reader $reader)
27
    {
28
        parent::__construct($reader);
29
        $this->methodConditionFetcher = new MethodConditionFetcher(Ensure::class);
30
    }
31
32
    /**
33
     * @param MethodInvocation $invocation
34
     * @throws ContractViolation
35
     * @return mixed
36
     */
37 8
    public function check(MethodInvocation $invocation)
38
    {
39 8
        $object = $invocation->getThis();
40 8
        $args   = $this->getMethodArguments($invocation);
41 8
        $class  = $invocation->getMethod()->getDeclaringClass();
42 8
        if ($class->isCloneable()) {
43 8
            $args['__old'] = clone $object;
44
        }
45
46 8
        $result = $invocation->proceed();
47 8
        $args['__result'] = $result;
48 8
        $allContracts = $this->makeContractsUnique($this->fetchAllContracts($invocation));
49
50 8
        $this->fulfillContracts($allContracts, $object, $class->name, $args, $invocation);
51
52 3
        return $result;
53
    }
54
55
    /**
56
     * @param MethodInvocation $invocation
57
     * @return array
58
     */
59 8
    private function fetchAllContracts(MethodInvocation $invocation)
60
    {
61 8
        $allContracts = $this->fetchParentsContracts($invocation);
62 8
        foreach ($invocation->getMethod()->getAnnotations() as $annotation) {
63 8
            if ($annotation instanceof Ensure) {
64 8
                $allContracts[] = $annotation;
65
            }
66
        }
67
68 8
        return $allContracts;
69
    }
70
71
    /**
72
     * @param MethodInvocation $invocation
73
     * @return array
74
     */
75 8
    private function fetchParentsContracts(MethodInvocation $invocation)
76
    {
77 8
        return $this->methodConditionFetcher->getConditions(
78 8
            $invocation->getMethod()->getDeclaringClass(),
79 8
            $this->reader,
80 8
            $invocation->getMethod()->name
81
        );
82
    }
83
}
84