AuraSqlConnectionInterceptor   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 54
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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