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

AuraSqlConnectionInterceptor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 2
rs 10
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