Completed
Push — master ( bf4fc0...a3a907 )
by Tomáš
03:11
created

DoctrineExtension::loadConfiguration()   B

Complexity

Conditions 8
Paths 128

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 44
CRAP Score 8.1105

Importance

Changes 0
Metric Value
dl 0
loc 78
ccs 44
cts 50
cp 0.88
rs 7.0488
c 0
b 0
f 0
cc 8
nc 128
nop 0
crap 8.1105

How to fix   Long Method   

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