TransactionalInterceptor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\AuraSqlModule;
6
7
use Aura\Sql\ExtendedPdoInterface;
8
use PDOException;
9
use Ray\Aop\MethodInterceptor;
10
use Ray\Aop\MethodInvocation;
11
use Ray\Aop\ReflectionMethod;
12
use Ray\AuraSqlModule\Annotation\Transactional;
13
use Ray\AuraSqlModule\Exception\RollbackException;
14
15
use function assert;
16
use function count;
17
use function is_array;
18
19
class TransactionalInterceptor implements MethodInterceptor
20
{
21
    private ?ExtendedPdoInterface $pdo;
22
23
    public function __construct(?ExtendedPdoInterface $pdo = null)
24
    {
25
        $this->pdo = $pdo;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function invoke(MethodInvocation $invocation)
32
    {
33
        $method = $invocation->getMethod();
34
        assert($method instanceof ReflectionMethod);
35
        $transactional = $method->getAnnotation(Transactional::class);
36
        assert($transactional instanceof Transactional);
37
        if (is_array($transactional->value) && count((array) $transactional->value) > 1) {
38
            return (new PropTransaction())($invocation, $transactional);
0 ignored issues
show
Deprecated Code introduced by
The class Ray\AuraSqlModule\PropTransaction has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

38
            return (/** @scrutinizer ignore-deprecated */ new PropTransaction())($invocation, $transactional);
Loading history...
39
        }
40
41
        if (! $this->pdo instanceof ExtendedPdoInterface) {
42
            return $invocation->proceed();
43
        }
44
45
        try {
46
            $this->pdo->beginTransaction();
47
            $result = $invocation->proceed();
48
            $this->pdo->commit();
49
        } catch (PDOException $e) {
50
            $this->pdo->rollBack();
51
52
            throw new RollbackException($e->getMessage(), 0, $e);
53
        }
54
55
        return $result;
56
    }
57
}
58