Passed
Push — support-php-8.2-8.3 ( ae3b12...8c2247 )
by Akihito
01:21
created

AuraSqlConnectionInterceptor::getConnection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
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
        $ref->setValue($object, $connection);
40
41
        return $invocation->proceed();
42
    }
43
44
    /** @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
            return $this->connectionLocator->getRead();
50
        }
51
52
        return $this->connectionLocator->getWrite();
53
    }
54
}
55