Completed
Push — master ( e4f263...4006c9 )
by Tomáš
02:05
created

DoctrineExtension   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 361
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 73.18%

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 2
dl 0
loc 361
ccs 131
cts 179
cp 0.7318
rs 8.295
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
B loadConfiguration() 0 66 6
B beforeCompile() 0 29 3
A afterCompile() 0 15 3
B processSecondLevelCache() 0 44 3
B getCache() 0 22 5
B parseConfig() 0 26 5
A hasIBarPanelInterface() 0 4 1
A hasPortinyConsole() 0 4 1
A hasEventManager() 0 5 2
A processDbalTypes() 0 12 2
A processDbalTypeOverrides() 0 9 2
A processEventSubscribers() 0 17 3
A processFilters() 0 9 2
B registerCommandsIntoConsole() 0 28 4

How to fix   Complexity   

Complex Class

Complex classes like DoctrineExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DoctrineExtension, and based on these observations, apply Extract Interface, too.

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