Passed
Pull Request — 1.x (#88)
by Akihito
01:23
created

AuraSqlConnectionInterceptor   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 11
c 3
b 0
f 0
dl 0
loc 36
ccs 8
cts 8
cp 1
rs 10
wmc 4

3 Methods

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