|
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 Ray\Aop\MethodInterceptor; |
|
11
|
|
|
use Ray\Aop\MethodInvocation; |
|
12
|
|
|
use Ray\AuraSqlModule\Annotation\Read; |
|
13
|
|
|
use Ray\AuraSqlModule\Annotation\Write; |
|
14
|
|
|
|
|
15
|
|
|
class AuraSqlConnectionInterceptor implements MethodInterceptor |
|
16
|
|
|
{ |
|
17
|
|
|
const PROP = 'pdo'; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var ConnectionLocatorInterface |
|
21
|
|
|
*/ |
|
22
|
|
|
private $connectionLocator; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var array |
|
26
|
|
|
*/ |
|
27
|
|
|
private $readsMethods = []; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @var array |
|
31
|
|
|
*/ |
|
32
|
|
|
private $writeMethods = []; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param ConnectionLocatorInterface $connectionLocator |
|
36
|
|
|
* @param array $readMethods |
|
37
|
|
|
* @param array $writeMethods |
|
38
|
|
|
* |
|
39
|
|
|
* @Read("readMethods") |
|
40
|
|
|
* @Write("writeMethods") |
|
41
|
|
|
*/ |
|
42
|
9 |
|
public function __construct(ConnectionLocatorInterface $connectionLocator, array $readMethods, array $writeMethods) |
|
43
|
|
|
{ |
|
44
|
9 |
|
$this->connectionLocator = $connectionLocator; |
|
45
|
9 |
|
$this->readsMethods = $readMethods; |
|
46
|
9 |
|
$this->writeMethods = $writeMethods; |
|
47
|
9 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* {@inheritdoc} |
|
51
|
|
|
*/ |
|
52
|
3 |
|
public function invoke(MethodInvocation $invocation) |
|
53
|
|
|
{ |
|
54
|
3 |
|
$connection = $this->getConnection($invocation); |
|
55
|
3 |
|
$object = $invocation->getThis(); |
|
56
|
3 |
|
$ref = new \ReflectionProperty($object, self::PROP); |
|
57
|
3 |
|
$ref->setAccessible(true); |
|
58
|
3 |
|
$ref->setValue($object, $connection); |
|
59
|
|
|
|
|
60
|
3 |
|
return $invocation->proceed(); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param MethodInvocation $invocation |
|
65
|
|
|
* |
|
66
|
|
|
* @return \Aura\Sql\ExtendedPdoInterface |
|
67
|
|
|
*/ |
|
68
|
3 |
|
private function getConnection(MethodInvocation $invocation) |
|
69
|
|
|
{ |
|
70
|
3 |
|
$methodName = $invocation->getMethod()->name; |
|
71
|
3 |
|
if (in_array($methodName, $this->readsMethods)) { |
|
72
|
3 |
|
return $this->connectionLocator->getRead(); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
3 |
|
return $this->connectionLocator->getWrite(); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|