Completed
Push — master ( 61dd2a...9f8cf8 )
by Tomáš
05:22
created

DoctrineExtension::loadConfiguration()   D

Complexity

Conditions 10
Paths 256

Size

Total Lines 100

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 60
CRAP Score 10.0751

Importance

Changes 0
Metric Value
dl 0
loc 100
ccs 60
cts 66
cp 0.9091
rs 4.9066
c 0
b 0
f 0
cc 10
nc 256
nop 0
crap 10.0751

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Portiny\Doctrine\Adapter\Nette\DI;
6
7
use Doctrine\Common\Annotations\AnnotationReader;
8
use Doctrine\Common\Annotations\AnnotationRegistry;
9
use Doctrine\Common\Annotations\CachedReader;
10
use Doctrine\Common\Annotations\Reader;
11
use Doctrine\Common\Cache\ArrayCache;
12
use Doctrine\Common\Cache\RedisCache;
13
use Doctrine\Common\EventManager;
14
use Doctrine\Common\EventSubscriber;
15
use Doctrine\DBAL\Connection;
16
use Doctrine\DBAL\Tools\Console\Command\ImportCommand;
17
use Doctrine\ORM\Cache\CacheConfiguration;
18
use Doctrine\ORM\Cache\CacheFactory;
19
use Doctrine\ORM\Cache\DefaultCacheFactory;
20
use Doctrine\ORM\Cache\Logging\CacheLogger;
21
use Doctrine\ORM\Cache\Logging\CacheLoggerChain;
22
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
23
use Doctrine\ORM\Cache\RegionsConfiguration;
24
use Doctrine\ORM\Configuration;
25
use Doctrine\ORM\EntityManager;
26
use Doctrine\ORM\EntityManagerInterface;
27
use Doctrine\ORM\EntityRepository;
28
use Doctrine\ORM\Events;
29
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
30
use Doctrine\ORM\Mapping\UnderscoreNamingStrategy;
31
use Doctrine\ORM\Query\Filter\SQLFilter;
32
use Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand;
33
use Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand;
34
use Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand;
35
use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
36
use Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand;
37
use Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand;
38
use Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand;
39
use Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand;
40
use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
41
use Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand;
42
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
43
use Doctrine\ORM\Tools\ResolveTargetEntityListener;
44
use Nette\DI\CompilerExtension;
45
use Nette\DI\ContainerBuilder;
46
use Nette\DI\ServiceDefinition;
47
use Nette\DI\Statement;
48
use Nette\PhpGenerator\ClassType;
49
use Nette\PhpGenerator\PhpLiteral;
50
use Nette\Utils\AssertionException;
51
use Nette\Utils\Validators;
52
use Portiny\Doctrine\Adapter\Nette\Tracy\DoctrineSQLPanel;
53
use Portiny\Doctrine\Cache\DefaultCache;
54
use Portiny\Doctrine\Contract\Provider\ClassMappingProviderInterface;
55
use Portiny\Doctrine\Contract\Provider\EntitySourceProviderInterface;
56
use Symfony\Component\Console\Application;
57
use Symfony\Component\Console\Helper\HelperSet;
58
use Tracy\IBarPanel;
59
60
class DoctrineExtension extends CompilerExtension
61
{
62
	/**
63
	 * @var string
64
	 */
65
	private const DOCTRINE_SQL_PANEL = DoctrineSQLPanel::class;
66
67
	private $classMappings = [];
68
69
	private $entitySources = [];
70
71
	/**
72
	 * @var array
73
	 */
74
	private static $defaults = [
75
		'debug' => '%debugMode%',
76
		'dbal' => [
77
			'type_overrides' => [],
78
			'types' => [],
79
			'schema_filter' => NULL,
80
		],
81
		'prefix' => 'doctrine.default',
82
		'proxyDir' => '%tempDir%/cache/proxies',
83
		'proxyNamespace' => 'DoctrineProxies',
84
		'sourceDir' => NULL,
85
		'entityManagerClassName' => EntityManager::class,
86
		'defaultRepositoryClassName' => EntityRepository::class,
87
		'repositoryFactory' => NULL,
88
		'namingStrategy' => UnderscoreNamingStrategy::class,
89
		'sqlLogger' => NULL,
90
		'targetEntityMappings' => [],
91
		'metadata' => [],
92
		'functions' => [],
93
		// caches
94
		'metadataCache' => 'default',
95
		'queryCache' => 'default',
96
		'resultCache' => 'default',
97
		'hydrationCache' => 'default',
98
		'secondLevelCache' => [
99
			'enabled' => FALSE,
100
			'factoryClass' => DefaultCacheFactory::class,
101
			'driver' => 'default',
102
			'regions' => [
103
				'defaultLifetime' => 3600,
104
				'defaultLockLifetime' => 60,
105
			],
106
			'fileLockRegionDirectory' => '%tempDir%/cache/Doctrine.Cache.Locks',
107
			'logging' => '%debugMode%',
108
		],
109
		'cache' => [
110
			'redis' => [
111
				'class' => RedisCache::class,
112
			],
113
		],
114
	];
115
116
	/**
117
	 * {@inheritdoc}
118
	 */
119 1
	public function loadConfiguration(): void
120
	{
121 1
		$config = $this->parseConfig();
122
123 1
		$builder = $this->getContainerBuilder();
124 1
		$name = $config['prefix'];
125
126 1
		$builder->addDefinition($name . '.namingStrategy')
127 1
			->setType($config['namingStrategy']);
128
129 1
		$configurationDefinition = $builder->addDefinition($name . '.config')
130 1
			->setType(Configuration::class)
131 1
			->addSetup('setFilterSchemaAssetsExpression', [$config['dbal']['schema_filter']])
132 1
			->addSetup('setDefaultRepositoryClassName', [$config['defaultRepositoryClassName']])
133 1
			->addSetup('setProxyDir', [$config['proxyDir']])
134 1
			->addSetup('setProxyNamespace', [$config['proxyNamespace']])
135 1
			->addSetup('setAutoGenerateProxyClasses', [$config['debug']])
136 1
			->addSetup('setNamingStrategy', ['@' . $name . '.namingStrategy']);
137
138 1
		$builder->addDefinition($name . '.annotationReader')
139 1
			->setType(AnnotationReader::class)
140 1
			->setAutowired(false);
141
142 1
		$metadataCache = $this->getCache($name . '.metadata', $builder, $config['metadataCache'] ?: 'array');
143 1
		$builder->addDefinition($name . '.reader')
144 1
			->setType(Reader::class)
145 1
			->setFactory(CachedReader::class, ['@' . $name . '.annotationReader', $metadataCache, $config['debug']]);
146
147 1
		$builder->addDefinition($name . '.annotationDriver')
148 1
			->setFactory(AnnotationDriver::class, ['@' . $name . '.reader', array_values($this->entitySources)]);
149
150 1
		$configurationDefinition->addSetup('setMetadataDriverImpl', ['@' . $name . '.annotationDriver']);
151
152 1
		foreach ($config['functions'] as $functionName => $function) {
153 1
			$configurationDefinition->addSetup('addCustomStringFunction', [$functionName, $function]);
154
		}
155
156 1
		if ($config['repositoryFactory']) {
157
			$builder->addDefinition($name . '.repositoryFactory')
158
				->setType($config['repositoryFactory']);
159
			$configurationDefinition->addSetup('setRepositoryFactory', ['@' . $name . '.repositoryFactory']);
160
		}
161 1
		if ($config['sqlLogger']) {
162
			$builder->addDefinition($name . '.sqlLogger')
163
				->setType($config['sqlLogger']);
164
			$configurationDefinition->addSetup('setSQLLogger', ['@' . $name . '.sqlLogger']);
165
		}
166
167 1
		if ($config['metadataCache'] !== FALSE) {
168 1
			$configurationDefinition->addSetup(
169 1
				'setMetadataCacheImpl',
170 1
				[$this->getCache($name . '.metadata', $builder, $config['metadataCache'])]
171
			);
172
		}
173
174 1
		if ($config['queryCache'] !== FALSE) {
175 1
			$configurationDefinition->addSetup(
176 1
				'setQueryCacheImpl',
177 1
				[$this->getCache($name . '.query', $builder, $config['queryCache'])]
178
			);
179
		}
180
181 1
		if ($config['resultCache'] !== FALSE) {
182 1
			$configurationDefinition->addSetup(
183 1
				'setResultCacheImpl',
184 1
				[$this->getCache($name . '.ormResult', $builder, $config['resultCache'])]
185
			);
186
		}
187
188 1
		if ($config['hydrationCache'] !== FALSE) {
189 1
			$configurationDefinition->addSetup(
190 1
				'setHydrationCacheImpl',
191 1
				[$this->getCache($name . '.hydration', $builder, $config['hydrationCache'])]
192
			);
193
		}
194
195 1
		$this->processSecondLevelCache($name, $config['secondLevelCache']);
196
197 1
		$builder->addDefinition($name . '.connection')
198 1
			->setType(Connection::class)
199 1
			->setFactory('@' . $name . '.entityManager::getConnection');
200
201 1
		$builder->addDefinition($name . '.entityManager')
202 1
			->setType($config['entityManagerClassName'])
203 1
			->setFactory(
204 1
				$config['entityManagerClassName'] . '::create',
205 1
				[$config['connection'], '@' . $name . '.config', '@Doctrine\Common\EventManager']
206
			);
207
208 1
		$builder->addDefinition($name . '.resolver')
209 1
			->setType(ResolveTargetEntityListener::class);
210
211 1
		if ($this->hasIBarPanelInterface()) {
212 1
			$builder->addDefinition($this->prefix($name . '.diagnosticsPanel'))
213 1
				->setType(self::DOCTRINE_SQL_PANEL);
214
		}
215
216
		// import Doctrine commands into Symfony/Console if exists
217 1
		$this->registerCommandsIntoConsole($builder, $name);
218 1
	}
219
220
	/**
221
	 * {@inheritdoc}
222
	 */
223 1
	public function beforeCompile(): void
224
	{
225 1
		$config = $this->getConfig(self::$defaults);
226 1
		$name = $config['prefix'];
227
228 1
		$builder = $this->getContainerBuilder();
229
230 1
		foreach ($this->classMappings as $source => $target) {
231
			$builder->getDefinition($name . '.resolver')
232
				->addSetup('addResolveTargetEntity', [$source, $target, []]);
233
		}
234
235 1
		$this->processDbalTypes($name, $config['dbal']['types']);
236 1
		$this->processDbalTypeOverrides($name, $config['dbal']['type_overrides']);
237 1
		$this->processEventSubscribers($name);
238 1
		$this->processFilters();
239 1
	}
240
241
	/**
242
	 * {@inheritdoc}
243
	 */
244 1
	public function afterCompile(ClassType $classType): void
245
	{
246 1
		$initialize = $classType->methods['initialize'];
247
248 1
		$initialize->addBody('?::registerUniqueLoader("class_exists");', [new PhpLiteral(AnnotationRegistry::class)]);
249
250 1
		if ($this->hasIBarPanelInterface()) {
251 1
			$initialize->addBody('$this->getByType(\'' . self::DOCTRINE_SQL_PANEL . '\')->bindToBar();');
252
		}
253
254 1
		$builder = $this->getContainerBuilder();
255 1
		$filterDefinitions = $builder->findByType(SQLFilter::class);
256 1
		if ($filterDefinitions !== []) {
257
			$initialize->addBody(
258
				'$filterCollection = $this->getByType(\'' . EntityManagerInterface::class . '\')->getFilters();'
259
			);
260
			foreach (array_keys($filterDefinitions) as $name) {
261
				$initialize->addBody('$filterCollection->enable(\'' . $name . '\');');
262
			}
263
		}
264 1
	}
265
266 1
	protected function processSecondLevelCache($name, array $config): void
267
	{
268 1
		if (! $config['enabled']) {
269 1
			return;
270
		}
271
272
		$builder = $this->getContainerBuilder();
273
274
		$cacheService = $this->getCache($name . '.secondLevel', $builder, $config['driver']);
275
276
		$builder->addDefinition($this->prefix($name . '.cacheFactory'))
277
			->setType(CacheFactory::class)
278
			->setFactory($config['factoryClass'], [
279
				$this->prefix('@' . $name . '.cacheRegionsConfiguration'),
280
				$cacheService,
281
			])
282
			->addSetup('setFileLockRegionDirectory', [$config['fileLockRegionDirectory']]);
283
284
		$builder->addDefinition($this->prefix($name . '.cacheRegionsConfiguration'))
285
			->setFactory(RegionsConfiguration::class, [
286
				$config['regions']['defaultLifetime'],
287
				$config['regions']['defaultLockLifetime'],
288
			]);
289
290
		$logger = $builder->addDefinition($this->prefix($name . '.cacheLogger'))
291
			->setType(CacheLogger::class)
292
			->setFactory(CacheLoggerChain::class)
293
			->setAutowired(FALSE);
294
295
		if ($config['logging']) {
296
			$logger->addSetup('setLogger', ['statistics', new Statement(StatisticsCacheLogger::class)]);
297
		}
298
299
		$cacheConfigName = $this->prefix($name . '.ormCacheConfiguration');
300
		$builder->addDefinition($cacheConfigName)
301
			->setType(CacheConfiguration::class)
302
			->addSetup('setCacheFactory', [$this->prefix('@' . $name . '.cacheFactory')])
303
			->addSetup('setCacheLogger', [$this->prefix('@' . $name . '.cacheLogger')])
304
			->setAutowired(FALSE);
305
306
		$configuration = $builder->getDefinitionByType(Configuration::class);
307
		$configuration->addSetup('setSecondLevelCacheEnabled');
308
		$configuration->addSetup('setSecondLevelCacheConfiguration', ['@' . $cacheConfigName]);
309
	}
310
311
	/**
312
	 * @throws AssertionException
313
	 */
314 1
	private function parseConfig(): array
315
	{
316 1
		$config = $this->getConfig(self::$defaults);
317 1
		$this->classMappings = $config['targetEntityMappings'];
318 1
		$this->entitySources = $config['metadata'];
319
320 1
		foreach ($this->compiler->getExtensions() as $extension) {
321 1
			if ($extension instanceof ClassMappingProviderInterface) {
322
				$entityMapping = $extension->getClassMapping();
323
				Validators::assert($entityMapping, 'array');
324
				$this->classMappings = array_merge($this->classMappings, $entityMapping);
325
			}
326
327 1
			if ($extension instanceof EntitySourceProviderInterface) {
328
				$entitySource = $extension->getEntitySource();
329
				Validators::assert($entitySource, 'array');
330 1
				$this->entitySources = array_merge($this->entitySources, $entitySource);
331
			}
332
		}
333
334 1
		if ($config['sourceDir']) {
335
			$this->entitySources[] = $config['sourceDir'];
336
		}
337
338 1
		return $config;
339
	}
340
341 1
	private function getCache(string $prefix, ContainerBuilder $containerBuilder, string $cacheType): string
342
	{
343 1
		if ($containerBuilder->hasDefinition($prefix . '.cache')) {
344 1
			return '@' . $prefix . '.cache';
345
		}
346
347 1
		$config = $this->parseConfig();
348
349
		switch ($cacheType) {
350 1
			case 'redis':
351
				$cacheClass = $config['cache']['redis']['class'];
352
				break;
353
354 1
			case 'array':
355
				$cacheClass = ArrayCache::class;
356
				break;
357
358 1
			case 'default':
359
			default:
360 1
				$cacheClass = DefaultCache::class;
361 1
				break;
362
		}
363
364 1
		$cacheDefinition = $containerBuilder->addDefinition($prefix . '.cache')
365 1
			->setType($cacheClass);
366
367 1
		if ($cacheType === 'redis') {
368
			$redisConfig = $config['cache']['redis'];
369
370
			$containerBuilder->addDefinition($prefix . '.redis')
371
				->setType('\Redis')
372
				->setAutowired(FALSE)
373
				->addSetup('connect', [
374
					$redisConfig['host'] ?? '127.0.0.1',
375
					$redisConfig['port'] ?? null,
376
					$redisConfig['timeout'] ?? 0.0,
377
					$redisConfig['reserved'] ?? null,
378
					$redisConfig['retryInterval'] ?? 0,
379
				])
380
				->addSetup('select', [$redisConfig['database'] ?? 1]);
381
382
			$cacheDefinition->addSetup('setRedis', ['@' . $prefix . '.redis']);
383
		}
384
385 1
		return '@' . $prefix . '.cache';
386
	}
387
388 1
	private function hasIBarPanelInterface(): bool
389
	{
390 1
		return interface_exists(IBarPanel::class);
391
	}
392
393 1
	private function registerCommandsIntoConsole(ContainerBuilder $containerBuilder, string $name): void
394
	{
395 1
		if ($this->hasSymfonyConsole()) {
396
			$commands = [
397 1
				ConvertMappingCommand::class,
398
				CreateCommand::class,
399
				DropCommand::class,
400
				GenerateEntitiesCommand::class,
401
				GenerateProxiesCommand::class,
402
				ImportCommand::class,
403
				MetadataCommand::class,
404
				QueryCommand::class,
405
				ResultCommand::class,
406
				UpdateCommand::class,
407
				ValidateSchemaCommand::class,
408
			];
409 1
			foreach ($commands as $index => $command) {
410 1
				$containerBuilder->addDefinition($name . '.command.' . $index)
411 1
					->setType($command);
412
			}
413
414 1
			$helperSets = $containerBuilder->findByType(HelperSet::class);
415 1
			if (! empty($helperSets)) {
416
				/** @var ServiceDefinition $helperSet */
417
				$helperSet = reset($helperSets);
418
				$helperSet->addSetup('set', [new Statement(EntityManagerHelper::class), 'em']);
419
			}
420
		}
421 1
	}
422
423 1
	private function processDbalTypes(string $name, array $types): void
424
	{
425 1
		$builder = $this->getContainerBuilder();
426 1
		$entityManagerDefinition = $builder->getDefinition($name . '.entityManager');
427
428 1
		foreach ($types as $type => $className) {
429 1
			$entityManagerDefinition->addSetup(
430 1
				'if ( ! Doctrine\DBAL\Types\Type::hasType(?)) { Doctrine\DBAL\Types\Type::addType(?, ?); }',
431 1
				[$type, $type, $className]
432
			);
433
		}
434 1
	}
435
436 1
	private function processDbalTypeOverrides(string $name, array $types): void
437
	{
438 1
		$builder = $this->getContainerBuilder();
439 1
		$entityManagerDefinition = $builder->getDefinition($name . '.entityManager');
440
441 1
		foreach ($types as $type => $className) {
442 1
			$entityManagerDefinition->addSetup('Doctrine\DBAL\Types\Type::overrideType(?, ?);', [$type, $className]);
443
		}
444 1
	}
445
446 1
	private function processEventSubscribers(string $name): void
447
	{
448 1
		$builder = $this->getContainerBuilder();
449
450 1
		if ($this->hasEventManager($builder)) {
451
			$eventManagerDefinition = $builder->getDefinition($builder->getByType(EventManager::class))
452
				->addSetup('addEventListener', [Events::loadClassMetadata, '@' . $name . '.resolver']);
453
		} else {
454 1
			$eventManagerDefinition = $builder->addDefinition($name . '.eventManager')
455 1
				->setType(EventManager::class)
456 1
				->addSetup('addEventListener', [Events::loadClassMetadata, '@' . $name . '.resolver']);
457
		}
458
459 1
		foreach (array_keys($builder->findByType(EventSubscriber::class)) as $serviceName) {
460 1
			$eventManagerDefinition->addSetup('addEventSubscriber', ['@' . $serviceName]);
461
		}
462 1
	}
463
464 1
	private function processFilters(): void
465
	{
466 1
		$builder = $this->getContainerBuilder();
467
468 1
		$configurationService = $builder->getDefinitionByType(Configuration::class);
469 1
		foreach ($builder->findByType(SQLFilter::class) as $name => $filterDefinition) {
470
			$configurationService->addSetup('addFilter', [$name, $filterDefinition->getType()]);
471
		}
472 1
	}
473
474 1
	private function hasSymfonyConsole(): bool
475
	{
476 1
		return class_exists(Application::class);
477
	}
478
479 1
	private function hasEventManager(ContainerBuilder $containerBuilder): bool
480
	{
481 1
		$eventManagerServiceName = $containerBuilder->getByType(EventManager::class);
482 1
		return $eventManagerServiceName !== NULL && strlen($eventManagerServiceName) > 0;
483
	}
484
}
485