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
|
|
|
|