-
Notifications
You must be signed in to change notification settings - Fork 60
/
DoctrineTestCompilerPass.php
196 lines (161 loc) · 7.8 KB
/
DoctrineTestCompilerPass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
<?php
namespace DAMA\DoctrineTestBundle\DependencyInjection;
use DAMA\DoctrineTestBundle\Doctrine\Cache\Psr6StaticArrayCache;
use DAMA\DoctrineTestBundle\Doctrine\DBAL\Middleware;
use Doctrine\Common\Cache\Cache;
use Doctrine\DBAL\Connection;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class DoctrineTestCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$transactionalBehaviorEnabledConnections = $this->getTransactionEnabledConnectionNames($container);
$container->register('dama.doctrine.dbal.middleware', Middleware::class);
$cacheNames = [];
if ($container->getParameter('dama.'.Configuration::STATIC_META_CACHE)) {
$cacheNames[] = 'doctrine.orm.%s_metadata_cache';
}
if ($container->getParameter('dama.'.Configuration::STATIC_QUERY_CACHE)) {
$cacheNames[] = 'doctrine.orm.%s_query_cache';
}
$connectionNames = array_keys($container->getParameter('doctrine.connections'));
foreach ($connectionNames as $name) {
if (in_array($name, $transactionalBehaviorEnabledConnections, true)) {
$this->modifyConnectionService($container, $name);
}
foreach ($cacheNames as $cacheName) {
$cacheServiceId = sprintf($cacheName, $name);
if (!$container->has($cacheServiceId)) {
// might happen if ORM is not used
continue;
}
$definition = $container->findDefinition($cacheServiceId);
while (!$definition->getClass() && $definition instanceof ChildDefinition) {
$definition = $container->findDefinition($definition->getParent());
}
$this->registerStaticCache($container, $definition, $cacheServiceId);
}
}
$container->getParameterBag()->remove('dama.'.Configuration::ENABLE_STATIC_CONNECTION);
$container->getParameterBag()->remove('dama.'.Configuration::STATIC_META_CACHE);
$container->getParameterBag()->remove('dama.'.Configuration::STATIC_QUERY_CACHE);
}
private function modifyConnectionService(ContainerBuilder $container, string $name): void
{
$connectionDefinition = $container->getDefinition(sprintf('doctrine.dbal.%s_connection', $name));
if (!$this->hasSavepointsEnabled($connectionDefinition)) {
throw new \LogicException(sprintf('This bundle relies on savepoints for nested database transactions. You need to enable "use_savepoints" on the Doctrine DBAL config for connection "%s".', $name));
}
$connectionDefinition->replaceArgument(
0,
$this->getModifiedConnectionOptions($connectionDefinition->getArgument(0), $name),
);
$connectionConfig = $container->getDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name));
$methodCalls = $connectionConfig->getMethodCalls();
$middlewareRef = new Reference('dama.doctrine.dbal.middleware');
$hasMiddlewaresMethodCall = false;
foreach ($methodCalls as &$methodCall) {
if ($methodCall[0] === 'setMiddlewares') {
$hasMiddlewaresMethodCall = true;
// our middleware needs to be the first one here so we wrap the "native" driver
$methodCall[1][0] = array_merge([$middlewareRef], $methodCall[1][0]);
}
}
if (!$hasMiddlewaresMethodCall) {
$methodCalls[] = ['setMiddlewares', [[$middlewareRef]]];
}
$connectionConfig->setMethodCalls($methodCalls);
}
private function getModifiedConnectionOptions(array $options, string $name): array
{
$connectionOptions = array_merge($options, [
'dama.keep_static' => true,
'dama.connection_name' => $name,
]);
if (isset($connectionOptions['primary'])) {
$connectionOptions['primary'] = array_merge($connectionOptions['primary'], [
'dama.keep_static' => true,
'dama.connection_name' => $name,
]);
}
if (isset($connectionOptions['replica']) && is_array($connectionOptions['replica'])) {
foreach ($connectionOptions['replica'] as $replicaName => &$replica) {
$replica = array_merge($replica, [
'dama.keep_static' => true,
'dama.connection_name' => sprintf('%s.%s', $name, $replicaName),
]);
}
}
return $connectionOptions;
}
private function registerStaticCache(
ContainerBuilder $container,
Definition $originalCacheServiceDefinition,
string $cacheServiceId
): void {
$cache = new Definition();
$namespace = sha1($cacheServiceId);
if (is_a($originalCacheServiceDefinition->getClass(), CacheItemPoolInterface::class, true)) {
$cache->setClass(Psr6StaticArrayCache::class);
$cache->setArgument(0, $namespace); // make sure we have no key collisions
} elseif (is_a($originalCacheServiceDefinition->getClass(), Cache::class, true)) {
throw new \InvalidArgumentException(sprintf('Configuring "%s" caches is not supported anymore. Upgrade to PSR-6 caches instead.', Cache::class));
} else {
throw new \InvalidArgumentException(sprintf('Unsupported cache class "%s" found on service "%s".', $originalCacheServiceDefinition->getClass(), $cacheServiceId));
}
if ($container->hasAlias($cacheServiceId)) {
$container->removeAlias($cacheServiceId);
}
$container->setDefinition($cacheServiceId, $cache);
}
/**
* @return string[]
*/
private function getTransactionEnabledConnectionNames(ContainerBuilder $container): array
{
/** @var bool|array $enableStaticConnectionsConfig */
$enableStaticConnectionsConfig = $container->getParameter('dama.'.Configuration::ENABLE_STATIC_CONNECTION);
$connectionNames = array_keys($container->getParameter('doctrine.connections'));
if (is_array($enableStaticConnectionsConfig)) {
$this->validateConnectionNames(array_keys($enableStaticConnectionsConfig), $connectionNames);
}
$enabledConnections = [];
foreach ($connectionNames as $name) {
if ($enableStaticConnectionsConfig === true
|| isset($enableStaticConnectionsConfig[$name]) && $enableStaticConnectionsConfig[$name] === true
) {
$enabledConnections[] = $name;
}
}
return $enabledConnections;
}
/**
* @param string[] $configNames
* @param string[] $existingNames
*/
private function validateConnectionNames(array $configNames, array $existingNames): void
{
$unknown = array_diff($configNames, $existingNames);
if (count($unknown)) {
throw new \InvalidArgumentException(sprintf('Unknown doctrine dbal connection name(s): %s.', implode(', ', $unknown)));
}
}
private function hasSavepointsEnabled(Definition $connectionDefinition): bool
{
// DBAL 4 implicitly always enables savepoints
if (!method_exists(Connection::class, 'getEventManager')) {
return true;
}
foreach ($connectionDefinition->getMethodCalls() as $call) {
if ($call[0] === 'setNestTransactionsWithSavepoints' && isset($call[1][0]) && $call[1][0]) {
return true;
}
}
return false;
}
}