Completed
Push — 1.x ( 77936e...e60590 )
by Akihito
27:35 queued 25:37
created

TransactionalInterceptor::beginTransaction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
/**
3
 * This file is part of the Ray.AuraSqlModule package
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Ray\AuraSqlModule;
8
9
use Ray\Aop\MethodInterceptor;
10
use Ray\Aop\MethodInvocation;
11
use Ray\AuraSqlModule\Annotation\Transactional;
12
use Ray\AuraSqlModule\Exception\InvalidTransactionalPropertyException;
13
use Ray\AuraSqlModule\Exception\RollbackException;
14
15
class TransactionalInterceptor implements MethodInterceptor
16
{
17
    /**
18
     * {@inheritdoc}
19
     */
20 12
    public function invoke(MethodInvocation $invocation)
21
    {
22 12
        $transactional = $invocation->getMethod()->getAnnotation(Transactional::class);
23 12
        $object = $invocation->getThis();
24 12
        $transactions = [];
25
        /* @var $transactions \PDO[] */
26 12
        foreach ($transactional->value as $prop) {
27 12
            $transactions[] = $this->beginTransaction($object, $prop);
28
        }
29
        try {
30 9
            $result = $invocation->proceed();
31 6
            foreach ($transactions as $db) {
32 6
                $db->commit();
33
            }
34 3
        } catch (\Exception $e) {
35 3
            foreach ($transactions as $db) {
36 3
                $db->rollback();
37
            }
38 3
            throw new RollbackException($e, 0, $e);
39
        }
40
41 6
        return $result;
42
    }
43
44
    /**
45
     * @param $object
46
     * @param $prop
47
     *
48
     * @return \Pdo
49
     */
50
51
    /**
52
     * @param $object
53
     * @param $prop
54
     *
55
     * @return mixed
56
     * @throws InvalidTransactionalPropertyException
57
     */
58 12
    private function beginTransaction($object, $prop)
59
    {
60
        try {
61 12
            $ref = new \ReflectionProperty($object, $prop);
62 3
        } catch (\ReflectionException $e) {
63 3
            throw new InvalidTransactionalPropertyException($prop, 0, $e);
64
        }
65 9
        $ref->setAccessible(true);
66 9
        $db = $ref->getValue($object);
67 9
        $db->beginTransaction();
68
69 9
        return $db;
70
    }
71
}
72