Completed
Push — 1.x ( 076555...10270e )
by Akihito
33:04
created

TransactionalInterceptor::beginTransaction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 13
c 1
b 1
f 0
rs 9.4285
cc 2
eloc 9
nc 2
nop 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
    public function invoke(MethodInvocation $invocation)
21
    {
22
        $transactional = $invocation->getMethod()->getAnnotation(Transactional::class);
23
        $object = $invocation->getThis();
24
        $transactions = [];
25
        /* @var $transactions \PDO[] */
26
        foreach ($transactional->value as $prop) {
27
            $transactions[] = $this->beginTransaction($object, $prop);
28
        }
29
        try {
30
            $result = $invocation->proceed();
31
            foreach ($transactions as $db) {
32
                $db->commit();
33
            }
34
        } catch (\Exception $e) {
35
            foreach ($transactions as $db) {
36
                $db->rollback();
37
            }
38
            throw new RollbackException($e, 0, $e);
39
        }
40
41
        return $result;
42
    }
43
44
    /**
45
     * @param object $object the object having pdo
46
     * @param string $prop   the name of pdo property
47
     *
48
     * @return \Pdo
49
     * @throws InvalidTransactionalPropertyException
50
     */
51
    private function beginTransaction($object, $prop)
52
    {
53
        try {
54
            $ref = new \ReflectionProperty($object, $prop);
55
        } catch (\ReflectionException $e) {
56
            throw new InvalidTransactionalPropertyException($prop, 0, $e);
57
        }
58
        $ref->setAccessible(true);
59
        $db = $ref->getValue($object);
60
        $db->beginTransaction();
61
62
        return $db;
63
    }
64
}
65