Issues (41)

src/AuraSqlConnectionInterceptor.php (1 issue)

Labels
Severity
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 readonly class AuraSqlConnectionInterceptor implements MethodInterceptor
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 17 at column 6
Loading history...
18
{
19
    public const string 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