AuraSqlConnectionInterceptor   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 4
eloc 16
c 3
b 0
f 0
dl 0
loc 44
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getConnection() 0 8 2
A invoke() 0 9 1
A __construct() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\AuraSqlModule;
6
7
use Aura\Sql\ConnectionLocatorInterface;
8
use Aura\Sql\ExtendedPdoInterface;
9
use Ray\Aop\MethodInterceptor;
10
use Ray\Aop\MethodInvocation;
11
use Ray\AuraSqlModule\Annotation\Read;
12
use ReflectionProperty;
13
14
use function in_array;
15
16
class AuraSqlConnectionInterceptor implements MethodInterceptor
17
{
18
    public const PROP = 'pdo';
19
20
    private ConnectionLocatorInterface $connectionLocator;
21
22
    /** @var string[] */
23
    private array $readsMethods = [];
24
25
    /**
26
     * @phpstan-param array<string> $readMethods
27
     *
28
     * @Read("readMethods")
29
     */
30
    #[Read('readMethods')]
31
    public function __construct(ConnectionLocatorInterface $connectionLocator, array $readMethods)
32
    {
33
        $this->connectionLocator = $connectionLocator;
34
        $this->readsMethods = $readMethods;
35
    }
36
37
    /**
38
     * {@inheritDoc}
39
     */
40
    public function invoke(MethodInvocation $invocation)
41
    {
42
        $connection = $this->getConnection($invocation);
43
        $object = $invocation->getThis();
44
        $ref = new ReflectionProperty($object, self::PROP);
45
        $ref->setAccessible(true);
46
        $ref->setValue($object, $connection);
47
48
        return $invocation->proceed();
49
    }
50
51
    /** @param MethodInvocation<object> $invocation */
52
    private function getConnection(MethodInvocation $invocation): ExtendedPdoInterface
53
    {
54
        $methodName = $invocation->getMethod()->name;
55
        if (in_array($methodName, $this->readsMethods, true)) {
56
            return $this->connectionLocator->getRead();
57
        }
58
59
        return $this->connectionLocator->getWrite();
60
    }
61
}
62