Completed
Push — master ( 1b0c2e...ec30d5 )
by Tomáš
02:32
created

DoctrineExtension::hasIBarPanelInterface()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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