Completed
Push — master ( 79190c...730c63 )
by Tomáš
06:11
created

DoctrineExtension::loadConfiguration()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 67
ccs 42
cts 42
cp 1
rs 8.5896
c 0
b 0
f 0
cc 6
eloc 41
nc 32
nop 0
crap 6

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\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' => TRUE,
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
				[
150 1
					$config['connection'],
151 1
					'@' . $name . '.config',
152 1
					'@Doctrine\Common\EventManager',
153
				]
154
			);
155
156 1
		$builder->addDefinition($name . '.namingStrategy')
157 1
			->setType(UnderscoreNamingStrategy::class);
158
159 1
		$builder->addDefinition($name . '.resolver')
160 1
			->setType(ResolveTargetEntityListener::class);
161
162 1
		if ($this->hasIBarPanelInterface()) {
163 1
			$builder->addDefinition($this->prefix($name . '.diagnosticsPanel'))
164 1
				->setType(self::DOCTRINE_SQL_PANEL);
165
		}
166 1
	}
167
168
	/**
169
	 * {@inheritdoc}
170
	 */
171 1
	public function beforeCompile(): void
172
	{
173 1
		$config = $this->getConfig(self::$defaults);
174 1
		$name = $config['prefix'];
175
176 1
		$builder = $this->getContainerBuilder();
177 1
		$cache = $this->getCache($name, $builder, 'default');
178
179 1
		$configDefinition = $builder->getDefinition($name . '.config')
180 1
			->setFactory(
181 1
				'\Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration',
182
				[
183 1
					array_values($this->entitySources),
184 1
					$config['debug'],
185 1
					$config['proxyDir'],
186 1
					$cache,
187
					FALSE,
188
				]
189
			)
190 1
			->addSetup('setNamingStrategy', ['@' . $name . '.namingStrategy']);
191
192 1
		foreach ($config['functions'] as $functionName => $function) {
193 1
			$configDefinition->addSetup('addCustomStringFunction', [$functionName, $function]);
194
		}
195
196 1
		foreach ($this->classMappings as $source => $target) {
197
			$builder->getDefinition($name . '.resolver')
198
				->addSetup('addResolveTargetEntity', [$source, $target, []]);
199
		}
200
201 1
		$this->processDbalTypes($name, $config['dbal']['types']);
202 1
		$this->processDbalTypeOverrides($name, $config['dbal']['type_overrides']);
203 1
		$this->processEventSubscribers($name);
204 1
		$this->processFilters($name);
205
206
		// import Doctrine commands into Portiny/Console
207 1
		if ($this->hasPortinyConsole()) {
208
			$commands = [
209
				ConvertMappingCommand::class,
210
				CreateCommand::class,
211
				DropCommand::class,
212
				GenerateEntitiesCommand::class,
213
				GenerateProxiesCommand::class,
214
				ImportCommand::class,
215
				MetadataCommand::class,
216
				QueryCommand::class,
217
				ResultCommand::class,
218
				UpdateCommand::class,
219
				ValidateSchemaCommand::class,
220
			];
221
			foreach ($commands as $index => $command) {
222
				$builder->addDefinition($name . '.command.' . $index)
223
					->setType($command);
224
			}
225
226
			$helperSets = $builder->findByType(HelperSet::class);
227
			if ($helperSets) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $helperSets of type Nette\DI\ServiceDefinition[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
228
				$helperSet = reset($helperSets);
229
				$helperSet->addSetup('set', [new Statement(EntityManagerHelper::class), 'em']);
230
			}
231
		}
232 1
	}
233
234
	/**
235
	 * {@inheritdoc}
236
	 */
237 1
	public function afterCompile(ClassType $classType): void
238
	{
239 1
		$initialize = $classType->methods['initialize'];
240 1
		if ($this->hasIBarPanelInterface()) {
241 1
			$initialize->addBody('$this->getByType(\'' . self::DOCTRINE_SQL_PANEL . '\')->bindToBar();');
242
		}
243
244 1
		$initialize->addBody(
245 1
			'$filterCollection = $this->getByType(\'' . EntityManagerInterface::class . '\')->getFilters();'
246
		);
247 1
		$builder = $this->getContainerBuilder();
248 1
		foreach ($builder->findByType(SQLFilter::class) as $name => $filterDefinition) {
249
			$initialize->addBody('$filterCollection->enable(\'' . $name . '\');');
250
		}
251 1
	}
252
253 1
	protected function processSecondLevelCache($name, array $config): void
254
	{
255 1
		if (! $config['enabled']) {
256 1
			return;
257
		}
258
259
		$builder = $this->getContainerBuilder();
260
261
		$cacheService = $this->getCache($name . '.secondLevel', $builder, $config['driver']);
262
263
		$builder->addDefinition($this->prefix($name . '.cacheFactory'))
264
			->setType(CacheFactory::class)
265
			->setFactory($config['factoryClass'], [
266
				$this->prefix('@' . $name . '.cacheRegionsConfiguration'),
267
				$cacheService,
268
			])
269
			->addSetup('setFileLockRegionDirectory', [$config['fileLockRegionDirectory']]);
270
271
		$builder->addDefinition($this->prefix($name . '.cacheRegionsConfiguration'))
272
			->setFactory(RegionsConfiguration::class, [
273
				$config['regions']['defaultLifetime'],
274
				$config['regions']['defaultLockLifetime'],
275
			]);
276
277
		$logger = $builder->addDefinition($this->prefix($name . '.cacheLogger'))
278
			->setType(CacheLogger::class)
279
			->setFactory(CacheLoggerChain::class)
280
			->setAutowired(FALSE);
281
282
		if ($config['logging']) {
283
			$logger->addSetup('setLogger', ['statistics', new Statement(StatisticsCacheLogger::class)]);
284
		}
285
286
		$cacheConfigName = $this->prefix($name . '.ormCacheConfiguration');
287
		$builder->addDefinition($cacheConfigName)
288
			->setType(CacheConfiguration::class)
289
			->addSetup('setCacheFactory', [$this->prefix('@' . $name . '.cacheFactory')])
290
			->addSetup('setCacheLogger', [$this->prefix('@' . $name . '.cacheLogger')])
291
			->setAutowired(FALSE);
292
293
		$configuration = $builder->getDefinitionByType(Configuration::class);
294
		$configuration->addSetup('setSecondLevelCacheEnabled');
295
		$configuration->addSetup('setSecondLevelCacheConfiguration', ['@' . $cacheConfigName]);
296
	}
297
298 1
	private function getCache(string $prefix, ContainerBuilder $containerBuilder, string $cacheType): string
299
	{
300 1
		$cacheServiceName = $containerBuilder->getByType(Cache::class);
301 1
		if ($cacheServiceName !== NULL && strlen($cacheServiceName) > 0) {
302 1
			return '@' . $cacheServiceName;
303
		}
304
305 1
		$cacheClass = ArrayCache::class;
306 1
		if ($cacheType) {
307
			switch ($cacheType) {
308 1
				case 'default':
309
				default:
310 1
					$cacheClass = DefaultCache::class;
311 1
					break;
312
			}
313
		}
314
315 1
		$containerBuilder->addDefinition($prefix . '.cache')
316 1
			->setType($cacheClass);
317
318 1
		return '@' . $prefix . '.cache';
319
	}
320
321
	/**
322
	 * @throws AssertionException
323
	 */
324 1
	private function parseConfig(): array
325
	{
326 1
		$config = $this->getConfig(self::$defaults);
327 1
		$this->classMappings = $config['targetEntityMappings'];
328 1
		$this->entitySources = $config['metadata'];
329
330 1
		foreach ($this->compiler->getExtensions() as $extension) {
331 1
			if ($extension instanceof ClassMappingProviderInterface) {
332
				$entityMapping = $extension->getClassMapping();
333
				Validators::assert($entityMapping, 'array');
334
				$this->classMappings = array_merge($this->classMappings, $entityMapping);
335
			}
336
337 1
			if ($extension instanceof EntitySourceProviderInterface) {
338
				$entitySource = $extension->getEntitySource();
339
				Validators::assert($entitySource, 'array');
340 1
				$this->entitySources = array_merge($this->entitySources, $entitySource);
341
			}
342
		}
343
344 1
		if ($config['sourceDir']) {
345
			$this->entitySources[] = $config['sourceDir'];
346
		}
347
348 1
		return $config;
349
	}
350
351 1
	private function hasIBarPanelInterface(): bool
352
	{
353 1
		return interface_exists(IBarPanel::class);
354
	}
355
356 1
	private function hasPortinyConsole(): bool
357
	{
358 1
		return class_exists(ConsoleExtension::class);
359
	}
360
361 1
	private function hasEventManager(ContainerBuilder $containerBuilder): bool
362
	{
363 1
		$eventManagerServiceName = $containerBuilder->getByType(EventManager::class);
364 1
		return $eventManagerServiceName !== NULL && strlen($eventManagerServiceName) > 0;
365
	}
366
367 1
	private function processDbalTypes(string $name, array $types): void
368
	{
369 1
		$builder = $this->getContainerBuilder();
370 1
		$entityManagerDefinition = $builder->getDefinition($name . '.entityManager');
371
372 1
		foreach ($types as $type => $className) {
373 1
			$entityManagerDefinition->addSetup(
374 1
				'if ( ! Doctrine\DBAL\Types\Type::hasType(?)) { Doctrine\DBAL\Types\Type::addType(?, ?); }',
375 1
				[$type, $type, $className]
376
			);
377
		}
378 1
	}
379
380 1
	private function processDbalTypeOverrides(string $name, array $types): void
381
	{
382 1
		$builder = $this->getContainerBuilder();
383 1
		$entityManagerDefinition = $builder->getDefinition($name . '.entityManager');
384
385 1
		foreach ($types as $type => $className) {
386 1
			$entityManagerDefinition->addSetup('Doctrine\DBAL\Types\Type::overrideType(?, ?);', [$type, $className]);
387
		}
388 1
	}
389
390 1
	private function processEventSubscribers(string $name): void
391
	{
392 1
		$builder = $this->getContainerBuilder();
393
394 1
		if ($this->hasEventManager($builder)) {
395
			$eventManagerDefinition = $builder->getDefinition($builder->getByType(EventManager::class))
396
				->addSetup('addEventListener', [Events::loadClassMetadata, '@' . $name . '.resolver']);
397
		} else {
398 1
			$eventManagerDefinition = $builder->addDefinition($name . '.eventManager')
399 1
				->setType(EventManager::class)
400 1
				->addSetup('addEventListener', [Events::loadClassMetadata, '@' . $name . '.resolver']);
401
		}
402
403 1
		foreach (array_keys($builder->findByType(EventSubscriber::class)) as $serviceName) {
404 1
			$eventManagerDefinition->addSetup('addEventSubscriber', ['@' . $serviceName]);
405
		}
406 1
	}
407
408 1
	private function processFilters(string $name): void
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
409
	{
410 1
		$builder = $this->getContainerBuilder();
411
412 1
		$configurationService = $builder->getDefinitionByType(Configuration::class);
413 1
		foreach ($builder->findByType(SQLFilter::class) as $name => $filterDefinition) {
414
			$configurationService->addSetup('addFilter', [$name, $filterDefinition->getType()]);
415
		}
416 1
	}
417
}
418