Completed
Pull Request — master (#263)
by
unknown
02:36
created

OrmExtension::processRepositoryFactoryEntities()   D

Complexity

Conditions 9
Paths 18

Size

Total Lines 45
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 45
rs 4.909
cc 9
eloc 26
nc 18
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Kdyby (http://www.kdyby.org)
5
 *
6
 * Copyright (c) 2008 Filip Procházka ([email protected])
7
 *
8
 * For the full copyright and license information, please view the file license.txt that was distributed with this source code.
9
 */
10
11
namespace Kdyby\Doctrine\DI;
12
13
use Doctrine;
14
use Doctrine\Common\Proxy\AbstractProxyFactory;
15
use Kdyby;
16
use Kdyby\DoctrineCache\DI\Helpers as CacheHelpers;
17
use Nette;
18
use Nette\DI\Statement;
19
use Nette\PhpGenerator as Code;
20
use Nette\PhpGenerator\Method;
21
use Nette\Utils\Strings;
22
use Nette\Utils\Validators;
23
24
25
26
/**
27
 * @author Filip Procházka <[email protected]>
28
 */
29
class OrmExtension extends Nette\DI\CompilerExtension
30
{
31
32
	const ANNOTATION_DRIVER = 'annotations';
33
	const PHP_NAMESPACE = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\\\\]*';
34
	const TAG_CONNECTION = 'doctrine.connection';
35
	const TAG_ENTITY_MANAGER = 'doctrine.entityManager';
36
	const TAG_BIND_TO_MANAGER = 'doctrine.bindToManager';
37
	const TAG_REPOSITORY_ENTITY = 'doctrine.repositoryEntity';
38
39
	/**
40
	 * @var array
41
	 */
42
	public $managerDefaults = [
43
		'metadataCache' => 'default',
44
		'queryCache' => 'default',
45
		'resultCache' => 'default',
46
		'hydrationCache' => 'default',
47
		'secondLevelCache' => [
48
			'enabled' => FALSE,
49
			'factoryClass' => 'Doctrine\ORM\Cache\DefaultCacheFactory',
50
			'driver' => 'default',
51
			'regions' => [
52
				'defaultLifetime' => 3600,
53
				'defaultLockLifetime' => 60,
54
			],
55
			'fileLockRegionDirectory' => '%tempDir%/cache/Doctrine.Cache.Locks', // todo fix
56
			'logging' => '%debugMode%',
57
		],
58
		'classMetadataFactory' => 'Kdyby\Doctrine\Mapping\ClassMetadataFactory',
59
		'defaultRepositoryClassName' => 'Kdyby\Doctrine\EntityRepository',
60
		'repositoryFactoryClassName' => 'Kdyby\Doctrine\RepositoryFactory',
61
		'queryBuilderClassName' => 'Kdyby\Doctrine\QueryBuilder',
62
		'autoGenerateProxyClasses' => '%debugMode%',
63
		'namingStrategy' => 'Doctrine\ORM\Mapping\UnderscoreNamingStrategy',
64
		'quoteStrategy' => 'Doctrine\ORM\Mapping\DefaultQuoteStrategy',
65
		'entityListenerResolver' => 'Kdyby\Doctrine\Mapping\EntityListenerResolver',
66
		'proxyDir' => '%tempDir%/proxies',
67
		'proxyNamespace' => 'Kdyby\GeneratedProxy',
68
		'dql' => ['string' => [], 'numeric' => [], 'datetime' => [], 'hints' => []],
69
		'hydrators' => [],
70
		'metadata' => [],
71
		'filters' => [],
72
		'namespaceAlias' => [],
73
		'targetEntityMappings' => [],
74
	];
75
76
	/**
77
	 * @var array
78
	 */
79
	public $connectionDefaults = [
80
		'dbname' => NULL,
81
		'host' => '127.0.0.1',
82
		'port' => NULL,
83
		'user' => NULL,
84
		'password' => NULL,
85
		'charset' => 'UTF8',
86
		'driver' => 'pdo_mysql',
87
		'driverClass' => NULL,
88
		'options' => NULL,
89
		'path' => NULL,
90
		'memory' => NULL,
91
		'unix_socket' => NULL,
92
		'logging' => '%debugMode%',
93
		'platformService' => NULL,
94
		'defaultTableOptions' => [],
95
		'resultCache' => 'default',
96
		'types' => [],
97
		'schemaFilter' => NULL,
98
	];
99
100
	/**
101
	 * @var array
102
	 */
103
	public $metadataDriverClasses = [
104
		self::ANNOTATION_DRIVER => 'Kdyby\Doctrine\Mapping\AnnotationDriver',
105
		'static' => 'Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver',
106
		'yml' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
107
		'yaml' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
108
		'xml' => 'Doctrine\ORM\Mapping\Driver\XmlDriver',
109
		'db' => 'Doctrine\ORM\Mapping\Driver\DatabaseDriver',
110
	];
111
112
	/**
113
	 * @var array
114
	 */
115
	private $proxyAutoloaders = [];
116
117
	/**
118
	 * @var array
119
	 */
120
	private $targetEntityMappings = [];
121
122
	/**
123
	 * @var array
124
	 */
125
	private $configuredManagers = [];
126
127
	/**
128
	 * @var array
129
	 */
130
	private $managerConfigs = [];
131
132
	/**
133
	 * @var array
134
	 */
135
	private $configuredConnections = [];
136
137
	/**
138
	 * @var array
139
	 */
140
	private $postCompileRepositoriesQueue = [];
141
142
143
144
	public function loadConfiguration()
145
	{
146
		$this->proxyAutoloaders =
147
		$this->targetEntityMappings =
148
		$this->configuredConnections =
149
		$this->managerConfigs =
150
		$this->configuredManagers =
151
		$this->postCompileRepositoriesQueue = [];
152
153
		$extensions = array_filter($this->compiler->getExtensions(), function ($item) {
154
			return $item instanceof Kdyby\Annotations\DI\AnnotationsExtension;
155
		});
156
		if (empty($extensions)) {
157
			throw new Nette\Utils\AssertionException('You should register \'Kdyby\Annotations\DI\AnnotationsExtension\' before \'' . get_class($this) . '\'.', E_USER_NOTICE);
158
		}
159
160
		$builder = $this->getContainerBuilder();
161
		$config = $this->getConfig();
162
163
		$builder->parameters[$this->prefix('debug')] = !empty($config['debug']);
164
		if (isset($config['dbname']) || isset($config['driver']) || isset($config['connection'])) {
165
			$config = ['default' => $config];
166
			$defaults = ['debug' => $builder->parameters['debugMode']];
167
168
		} else {
169
			$defaults = array_intersect_key($config, $this->managerDefaults)
170
				+ array_intersect_key($config, $this->connectionDefaults)
171
				+ ['debug' => $builder->parameters['debugMode']];
172
173
			$config = array_diff_key($config, $defaults);
174
		}
175
176
		if (empty($config)) {
177
			throw new Kdyby\Doctrine\UnexpectedValueException("Please configure the Doctrine extensions using the section '{$this->name}:' in your config file.");
178
		}
179
180
		foreach ($config as $name => $emConfig) {
181
			if (!is_array($emConfig) || (empty($emConfig['dbname']) && empty($emConfig['driver']))) {
182
				throw new Kdyby\Doctrine\UnexpectedValueException("Please configure the Doctrine extensions using the section '{$this->name}:' in your config file.");
183
			}
184
185
			$emConfig = Nette\DI\Config\Helpers::merge($emConfig, $defaults);
186
			$this->processEntityManager($name, $emConfig);
0 ignored issues
show
Bug introduced by
It seems like $emConfig defined by \Nette\DI\Config\Helpers...e($emConfig, $defaults) on line 185 can also be of type string; however, Kdyby\Doctrine\DI\OrmExt...:processEntityManager() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
187
		}
188
189
		if ($this->targetEntityMappings) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->targetEntityMappings of type array 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...
190
			$listener = $builder->addDefinition($this->prefix('resolveTargetEntityListener'))
191
				->setClass('Kdyby\Doctrine\Tools\ResolveTargetEntityListener')
192
				->addTag(Kdyby\Events\DI\EventsExtension::SUBSCRIBER_TAG)
0 ignored issues
show
Deprecated Code introduced by
The constant Kdyby\Events\DI\EventsExtension::SUBSCRIBER_TAG has been deprecated.

This class constant has been deprecated.

Loading history...
193
				->setInject(FALSE);
194
195
			foreach ($this->targetEntityMappings as $originalEntity => $mapping) {
196
				$listener->addSetup('addResolveTargetEntity', [$originalEntity, $mapping['targetEntity'], $mapping]);
197
			}
198
		}
199
200
		$this->loadConsole();
201
202
		$builder->addDefinition($this->prefix('registry'))
203
			->setClass('Kdyby\Doctrine\Registry', [
204
				$this->configuredConnections,
205
				$this->configuredManagers,
206
				$builder->parameters[$this->name]['dbal']['defaultConnection'],
207
				$builder->parameters[$this->name]['orm']['defaultEntityManager'],
208
			]);
209
	}
210
211
212
213
	protected function loadConsole()
214
	{
215
		$builder = $this->getContainerBuilder();
216
217
		foreach ($this->loadFromFile(__DIR__ . '/console.neon') as $i => $command) {
0 ignored issues
show
Bug introduced by
The expression $this->loadFromFile(__DIR__ . '/console.neon') of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
218
			$cli = $builder->addDefinition($this->prefix('cli.' . $i))
219
				->addTag(Kdyby\Console\DI\ConsoleExtension::COMMAND_TAG)
0 ignored issues
show
Deprecated Code introduced by
The constant Kdyby\Console\DI\ConsoleExtension::COMMAND_TAG has been deprecated.

This class constant has been deprecated.

Loading history...
220
				->setInject(FALSE); // lazy injects
221
222
			if (is_string($command)) {
223
				$cli->setClass($command);
224
225
			} else {
226
				throw new Kdyby\Doctrine\NotSupportedException;
227
			}
228
		}
229
	}
230
231
232
233
	protected function processEntityManager($name, array $defaults)
234
	{
235
		$builder = $this->getContainerBuilder();
236
		$config = $this->resolveConfig($defaults, $this->managerDefaults, $this->connectionDefaults);
237
238
		if ($isDefault = !isset($builder->parameters[$this->name]['orm']['defaultEntityManager'])) {
239
			$builder->parameters[$this->name]['orm']['defaultEntityManager'] = $name;
240
		}
241
242
		$metadataDriver = $builder->addDefinition($this->prefix($name . '.metadataDriver'))
243
			->setClass('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain')
244
			->setAutowired(FALSE)
245
			->setInject(FALSE);
246
		/** @var Nette\DI\ServiceDefinition $metadataDriver */
247
248
		Validators::assertField($config, 'metadata', 'array');
249
		Validators::assertField($config, 'targetEntityMappings', 'array');
250
		$config['targetEntityMappings'] = $this->normalizeTargetEntityMappings($config['targetEntityMappings']);
251
		foreach ($this->compiler->getExtensions() as $extension) {
252
			if ($extension instanceof IEntityProvider) {
253
				$metadata = $extension->getEntityMappings();
254
				Validators::assert($metadata, 'array');
255
				$config['metadata'] = array_merge($config['metadata'], $metadata);
256
			}
257
258
			if ($extension instanceof ITargetEntityProvider) {
259
				$targetEntities = $extension->getTargetEntityMappings();
260
				Validators::assert($targetEntities, 'array');
261
				$config['targetEntityMappings'] = Nette\Utils\Arrays::mergeTree($config['targetEntityMappings'], $this->normalizeTargetEntityMappings($targetEntities));
262
			}
263
264
			if ($extension instanceof IDatabaseTypeProvider) {
265
				$providedTypes = $extension->getDatabaseTypes();
266
				Validators::assert($providedTypes, 'array');
267
268
				if (!isset($defaults['types'])) {
269
					$defaults['types'] = [];
270
				}
271
272
				$defaults['types'] = array_merge($defaults['types'], $providedTypes);
273
			}
274
		}
275
276
		foreach (self::natSortKeys($config['metadata']) as $namespace => $driver) {
277
			$this->processMetadataDriver($metadataDriver, $namespace, $driver, $name);
278
		}
279
280
		$this->processMetadataDriver($metadataDriver, 'Kdyby\\Doctrine', __DIR__ . '/../Entities', $name);
281
282
		if (empty($config['metadata'])) {
283
			$metadataDriver->addSetup('setDefaultDriver', [
284
				new Statement($this->metadataDriverClasses[self::ANNOTATION_DRIVER], [
285
					[$builder->expand('%appDir%')],
0 ignored issues
show
Deprecated Code introduced by
The method Nette\DI\ContainerBuilder::expand() has been deprecated.

This method has been deprecated.

Loading history...
286
					2 => $this->prefix('@cache.' . $name . '.metadata')
287
				])
288
			]);
289
		}
290
291
		if ($config['repositoryFactoryClassName'] === 'default') {
292
			$config['repositoryFactoryClassName'] = 'Doctrine\ORM\Repository\DefaultRepositoryFactory';
293
		}
294
		$builder->addDefinition($this->prefix($name . '.repositoryFactory'))
295
			->setClass($config['repositoryFactoryClassName'])
296
			->setAutowired(FALSE);
297
298
		Validators::assertField($config, 'namespaceAlias', 'array');
299
		Validators::assertField($config, 'hydrators', 'array');
300
		Validators::assertField($config, 'dql', 'array');
301
		Validators::assertField($config['dql'], 'string', 'array');
302
		Validators::assertField($config['dql'], 'numeric', 'array');
303
		Validators::assertField($config['dql'], 'datetime', 'array');
304
		Validators::assertField($config['dql'], 'hints', 'array');
305
306
		$autoGenerateProxyClasses = is_bool($config['autoGenerateProxyClasses'])
307
			? ($config['autoGenerateProxyClasses'] ? AbstractProxyFactory::AUTOGENERATE_ALWAYS : AbstractProxyFactory::AUTOGENERATE_NEVER)
308
			: $config['autoGenerateProxyClasses'];
309
310
		$configuration = $builder->addDefinition($this->prefix($name . '.ormConfiguration'))
311
			->setClass('Kdyby\Doctrine\Configuration')
312
			->addSetup('setMetadataCacheImpl', [$this->processCache($config['metadataCache'], $name . '.metadata')])
313
			->addSetup('setQueryCacheImpl', [$this->processCache($config['queryCache'], $name . '.query')])
314
			->addSetup('setResultCacheImpl', [$this->processCache($config['resultCache'], $name . '.ormResult')])
315
			->addSetup('setHydrationCacheImpl', [$this->processCache($config['hydrationCache'], $name . '.hydration')])
316
			->addSetup('setMetadataDriverImpl', [$this->prefix('@' . $name . '.metadataDriver')])
317
			->addSetup('setClassMetadataFactoryName', [$config['classMetadataFactory']])
318
			->addSetup('setDefaultRepositoryClassName', [$config['defaultRepositoryClassName']])
319
			->addSetup('setQueryBuilderClassName', [$config['queryBuilderClassName']])
320
			->addSetup('setRepositoryFactory', [$this->prefix('@' . $name . '.repositoryFactory')])
321
			->addSetup('setProxyDir', [$config['proxyDir']])
322
			->addSetup('setProxyNamespace', [$config['proxyNamespace']])
323
			->addSetup('setAutoGenerateProxyClasses', [$autoGenerateProxyClasses])
324
			->addSetup('setEntityNamespaces', [$config['namespaceAlias']])
325
			->addSetup('setCustomHydrationModes', [$config['hydrators']])
326
			->addSetup('setCustomStringFunctions', [$config['dql']['string']])
327
			->addSetup('setCustomNumericFunctions', [$config['dql']['numeric']])
328
			->addSetup('setCustomDatetimeFunctions', [$config['dql']['datetime']])
329
			->addSetup('setDefaultQueryHints', [$config['dql']['hints']])
330
			->addSetup('setNamingStrategy', CacheHelpers::filterArgs($config['namingStrategy']))
331
			->addSetup('setQuoteStrategy', CacheHelpers::filterArgs($config['quoteStrategy']))
332
			->addSetup('setEntityListenerResolver', CacheHelpers::filterArgs($config['entityListenerResolver']))
333
			->setAutowired(FALSE)
334
			->setInject(FALSE);
335
		/** @var Nette\DI\ServiceDefinition $configuration */
336
337
		$this->proxyAutoloaders[$config['proxyNamespace']] = $config['proxyDir'];
338
339
		$this->processSecondLevelCache($name, $config['secondLevelCache'], $isDefault);
340
341
		Validators::assertField($config, 'filters', 'array');
342
		foreach ($config['filters'] as $filterName => $filterClass) {
343
			$configuration->addSetup('addFilter', [$filterName, $filterClass]);
344
		}
345
346
		if ($config['targetEntityMappings']) {
347
			$configuration->addSetup('setTargetEntityMap', [array_map(function ($mapping) {
348
				return $mapping['targetEntity'];
349
			}, $config['targetEntityMappings'])]);
350
			$this->targetEntityMappings = Nette\Utils\Arrays::mergeTree($this->targetEntityMappings, $config['targetEntityMappings']);
351
		}
352
353
		$builder->addDefinition($this->prefix($name . '.evm'))
354
			->setClass('Kdyby\Events\NamespacedEventManager', [Kdyby\Doctrine\Events::NS . '::'])
355
			->addSetup('$dispatchGlobalEvents', [TRUE]) // for BC
356
			->setAutowired(FALSE);
357
358
		// entity manager
359
		$entityManager = $builder->addDefinition($managerServiceId = $this->prefix($name . '.entityManager'))
360
			->setClass('Kdyby\Doctrine\EntityManager')
361
			->setFactory('Kdyby\Doctrine\EntityManager::create', [
362
				$connectionService = $this->processConnection($name, $defaults, $isDefault),
363
				$this->prefix('@' . $name . '.ormConfiguration'),
364
				$this->prefix('@' . $name . '.evm'),
365
			])
366
			->addTag(self::TAG_ENTITY_MANAGER)
367
			->addTag('kdyby.doctrine.entityManager')
368
			->setAutowired($isDefault)
369
			->setInject(FALSE);
370
371
		if ($this->isTracyPresent()) {
372
			$entityManager->addSetup('?->bindEntityManager(?)', [$this->prefix('@' . $name . '.diagnosticsPanel'), '@self']);
373
		}
374
375
		$builder->addDefinition($this->prefix('repositoryFactory.' . $name . '.defaultRepositoryFactory'))
376
				->setClass($config['defaultRepositoryClassName'])
377
				->setImplement('Kdyby\Doctrine\DI\IRepositoryFactory')
378
				->setArguments([new Code\PhpLiteral('$entityManager'), new Code\PhpLiteral('$classMetadata')])
379
				->setParameters(['Doctrine\ORM\EntityManagerInterface entityManager', 'Doctrine\ORM\Mapping\ClassMetadata classMetadata'])
380
				->setAutowired(FALSE);
381
382
		$builder->addDefinition($this->prefix($name . '.schemaValidator'))
383
			->setClass('Doctrine\ORM\Tools\SchemaValidator', ['@' . $managerServiceId])
384
			->setAutowired($isDefault);
385
386
		$builder->addDefinition($this->prefix($name . '.schemaTool'))
387
			->setClass('Doctrine\ORM\Tools\SchemaTool', ['@' . $managerServiceId])
388
			->setAutowired($isDefault);
389
390
		$cacheCleaner = $builder->addDefinition($this->prefix($name . '.cacheCleaner'))
391
			->setClass('Kdyby\Doctrine\Tools\CacheCleaner', ['@' . $managerServiceId])
392
			->setAutowired($isDefault);
393
394
		$builder->addDefinition($this->prefix($name . '.schemaManager'))
395
			->setClass('Doctrine\DBAL\Schema\AbstractSchemaManager')
396
			->setFactory('@Kdyby\Doctrine\Connection::getSchemaManager')
397
			->setAutowired($isDefault);
398
399
		foreach ($this->compiler->getExtensions('Kdyby\Annotations\DI\AnnotationsExtension') as $extension) {
400
			/** @var Kdyby\Annotations\DI\AnnotationsExtension $extension */
401
			$cacheCleaner->addSetup('addCacheStorage', [$extension->prefix('@cache.annotations')]);
402
		}
403
404
		if ($isDefault) {
405
			$builder->addDefinition($this->prefix('helper.entityManager'))
406
				->setClass('Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper', ['@' . $managerServiceId])
407
				->addTag(Kdyby\Console\DI\ConsoleExtension::HELPER_TAG, 'em');
0 ignored issues
show
Documentation introduced by
'em' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The constant Kdyby\Console\DI\ConsoleExtension::HELPER_TAG has been deprecated.

This class constant has been deprecated.

Loading history...
408
409
			$builder->addDefinition($this->prefix('helper.connection'))
410
				->setClass('Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper', [$connectionService])
411
				->addTag(Kdyby\Console\DI\ConsoleExtension::HELPER_TAG, 'db');
0 ignored issues
show
Documentation introduced by
'db' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The constant Kdyby\Console\DI\ConsoleExtension::HELPER_TAG has been deprecated.

This class constant has been deprecated.

Loading history...
412
413
			$builder->addAlias($this->prefix('schemaValidator'), $this->prefix($name . '.schemaValidator'));
414
			$builder->addAlias($this->prefix('schemaTool'), $this->prefix($name . '.schemaTool'));
415
			$builder->addAlias($this->prefix('cacheCleaner'), $this->prefix($name . '.cacheCleaner'));
416
			$builder->addAlias($this->prefix('schemaManager'), $this->prefix($name . '.schemaManager'));
417
		}
418
419
		$this->configuredManagers[$name] = $managerServiceId;
420
		$this->managerConfigs[$name] = $config;
421
	}
422
423
424
425
	protected function processSecondLevelCache($name, array $config, $isDefault)
426
	{
427
		if (!$config['enabled']) {
428
			return;
429
		}
430
431
		$builder = $this->getContainerBuilder();
432
433
		$cacheFactory = $builder->addDefinition($this->prefix($name . '.cacheFactory'))
434
			->setClass('Doctrine\ORM\Cache\CacheFactory')
435
			->setFactory($config['factoryClass'], [
436
				$this->prefix('@' . $name . '.cacheRegionsConfiguration'),
437
				$this->processCache($config['driver'], $name . '.secondLevel'),
438
			])
439
			->setAutowired($isDefault);
440
441
		if ($config['factoryClass'] === $this->managerDefaults['secondLevelCache']['factoryClass']
442
			|| is_subclass_of($config['factoryClass'], $this->managerDefaults['secondLevelCache']['factoryClass'])
443
		) {
444
			$cacheFactory->addSetup('setFileLockRegionDirectory', [$config['fileLockRegionDirectory']]);
445
		}
446
447
		$builder->addDefinition($this->prefix($name . '.cacheRegionsConfiguration'))
448
			->setClass('Doctrine\ORM\Cache\RegionsConfiguration', [
449
				$config['regions']['defaultLifetime'],
450
				$config['regions']['defaultLockLifetime'],
451
			])
452
			->setAutowired($isDefault);
453
454
		$logger = $builder->addDefinition($this->prefix($name . '.cacheLogger'))
455
			->setClass('Doctrine\ORM\Cache\Logging\CacheLogger')
456
			->setFactory('Doctrine\ORM\Cache\Logging\CacheLoggerChain')
457
			->setAutowired(FALSE);
458
459
		if ($config['logging']) {
460
			$logger->addSetup('setLogger', [
461
				'statistics',
462
				new Statement('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger')
463
			]);
464
		}
465
466
		$builder->addDefinition($cacheConfigName = $this->prefix($name . '.ormCacheConfiguration'))
467
			->setClass('Doctrine\ORM\Cache\CacheConfiguration')
468
			->addSetup('setCacheFactory', [$this->prefix('@' . $name . '.cacheFactory')])
469
			->addSetup('setCacheLogger', [$this->prefix('@' . $name . '.cacheLogger')])
470
			->setAutowired($isDefault);
471
472
		$configuration = $builder->getDefinition($this->prefix($name . '.ormConfiguration'));
473
		$configuration->addSetup('setSecondLevelCacheEnabled');
474
		$configuration->addSetup('setSecondLevelCacheConfiguration', ['@' . $cacheConfigName]);
475
	}
476
477
478
479
	protected function processConnection($name, array $defaults, $isDefault = FALSE)
480
	{
481
		$builder = $this->getContainerBuilder();
482
		$config = $this->resolveConfig($defaults, $this->connectionDefaults, $this->managerDefaults);
483
484
		if ($isDefault) {
485
			$builder->parameters[$this->name]['dbal']['defaultConnection'] = $name;
486
		}
487
488
		if (isset($defaults['connection'])) {
489
			return $this->prefix('@' . $defaults['connection'] . '.connection');
490
		}
491
492
		// config
493
		$configuration = $builder->addDefinition($this->prefix($name . '.dbalConfiguration'))
494
			->setClass('Doctrine\DBAL\Configuration')
495
			->addSetup('setResultCacheImpl', [$this->processCache($config['resultCache'], $name . '.dbalResult')])
496
			->addSetup('setSQLLogger', [new Statement('Doctrine\DBAL\Logging\LoggerChain')])
497
			->addSetup('setFilterSchemaAssetsExpression', [$config['schemaFilter']])
498
			->setAutowired(FALSE)
499
			->setInject(FALSE);
500
501
		// types
502
		Validators::assertField($config, 'types', 'array');
503
		$schemaTypes = $dbalTypes = [];
504
		foreach ($config['types'] as $dbType => $className) {
505
			$typeInst = Code\Helpers::createObject($className, []);
506
			/** @var Doctrine\DBAL\Types\Type $typeInst */
507
			$dbalTypes[$typeInst->getName()] = $className;
508
			$schemaTypes[$dbType] = $typeInst->getName();
509
		}
510
511
		// tracy panel
512
		if ($this->isTracyPresent()) {
513
			$builder->addDefinition($this->prefix($name . '.diagnosticsPanel'))
514
				->setClass('Kdyby\Doctrine\Diagnostics\Panel')
515
				->setAutowired(FALSE);
516
		}
517
518
		// connection
519
		$options = array_diff_key($config, array_flip(['types', 'resultCache', 'connection', 'logging']));
520
		$connection = $builder->addDefinition($connectionServiceId = $this->prefix($name . '.connection'))
521
			->setClass('Kdyby\Doctrine\Connection')
522
			->setFactory('Kdyby\Doctrine\Connection::create', [
523
				$options,
524
				$this->prefix('@' . $name . '.dbalConfiguration'),
525
				$this->prefix('@' . $name . '.evm')
526
			])
527
			->addSetup('setSchemaTypes', [$schemaTypes])
528
			->addSetup('setDbalTypes', [$dbalTypes])
529
			->addTag(self::TAG_CONNECTION)
530
			->addTag('kdyby.doctrine.connection')
531
			->setAutowired($isDefault)
532
			->setInject(FALSE);
533
534
		if ($this->isTracyPresent()) {
535
			$connection->addSetup('$panel = ?->bindConnection(?)', [$this->prefix('@' . $name . '.diagnosticsPanel'), '@self']);
536
		}
537
538
		/** @var Nette\DI\ServiceDefinition $connection */
539
540
		$this->configuredConnections[$name] = $connectionServiceId;
541
542
		if (!is_bool($config['logging'])) {
543
			$fileLogger = new Statement('Kdyby\Doctrine\Diagnostics\FileLogger', [$builder->expand($config['logging'])]);
0 ignored issues
show
Deprecated Code introduced by
The method Nette\DI\ContainerBuilder::expand() has been deprecated.

This method has been deprecated.

Loading history...
544
			$configuration->addSetup('$service->getSQLLogger()->addLogger(?)', [$fileLogger]);
545
546
		} elseif ($config['logging']) {
547
			$connection->addSetup('?->enableLogging()', [new Code\PhpLiteral('$panel')]);
548
		}
549
550
		return $this->prefix('@' . $name . '.connection');
551
	}
552
553
554
555
	/**
556
	 * @param \Nette\DI\ServiceDefinition $metadataDriver
557
	 * @param string $namespace
558
	 * @param string|object $driver
559
	 * @param string $prefix
560
	 * @throws \Nette\Utils\AssertionException
561
	 * @return string
562
	 */
563
	protected function processMetadataDriver(Nette\DI\ServiceDefinition $metadataDriver, $namespace, $driver, $prefix)
564
	{
565
		if (!is_string($namespace) || !Strings::match($namespace, '#^' . self::PHP_NAMESPACE . '\z#')) {
566
			throw new Nette\Utils\AssertionException("The metadata namespace expects to be valid namespace, $namespace given.");
567
		}
568
		$namespace = ltrim($namespace, '\\');
569
570
		if (is_string($driver) || is_array($driver)) {
571
			$paths = is_array($driver) ? $driver : [$driver];
572
			foreach ($paths as $path) {
573
				if (($pos = strrpos($path, '*')) !== FALSE) {
574
					$path = substr($path, 0, $pos);
575
				}
576
577
				if (!file_exists($path)) {
578
					throw new Nette\Utils\AssertionException("The metadata path expects to be an existing directory, $path given.");
579
				}
580
			}
581
582
			$driver = new Statement(self::ANNOTATION_DRIVER, is_array($paths) ? $paths : [$paths]);
583
		}
584
585
		$impl = $driver instanceof \stdClass ? $driver->value : ($driver instanceof Statement ? $driver->entity : (string) $driver);
586
		list($driver) = CacheHelpers::filterArgs($driver);
587
		/** @var Statement $driver */
588
589
		if (isset($this->metadataDriverClasses[$impl])) {
590
			$driver->entity = $this->metadataDriverClasses[$impl];
591
		}
592
593
		if (is_string($driver->entity) && substr($driver->entity, 0, 1) === '@') {
594
			$metadataDriver->addSetup('addDriver', [$driver->entity, $namespace]);
595
			return $driver->entity;
596
		}
597
598
		if ($impl === self::ANNOTATION_DRIVER) {
599
			$driver->arguments = [
600
				Nette\Utils\Arrays::flatten($driver->arguments),
601
				2 => $this->prefix('@cache.' . $prefix . '.metadata')
602
			];
603
		}
604
605
		$serviceName = $this->prefix($prefix . '.driver.' . str_replace('\\', '_', $namespace) . '.' . str_replace('\\', '_', $impl) . 'Impl');
606
607
		$this->getContainerBuilder()->addDefinition($serviceName)
608
			->setClass('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver')
609
			->setFactory($driver->entity, $driver->arguments)
610
			->setAutowired(FALSE)
611
			->setInject(FALSE);
612
613
		$metadataDriver->addSetup('addDriver', ['@' . $serviceName, $namespace]);
614
		return '@' . $serviceName;
615
	}
616
617
618
619
	/**
620
	 * @param string|\stdClass $cache
621
	 * @param string $suffix
622
	 * @return string
623
	 */
624
	protected function processCache($cache, $suffix)
625
	{
626
		return CacheHelpers::processCache($this, $cache, $suffix, $this->getContainerBuilder()->parameters[$this->prefix('debug')]);
627
	}
628
629
630
631
	public function beforeCompile()
632
	{
633
		$eventsExt = NULL;
634
		foreach ($this->compiler->getExtensions() as $extension) {
635
			if ($extension instanceof Kdyby\Events\DI\EventsExtension) {
636
				$eventsExt = $extension;
637
				break;
638
			}
639
		}
640
641
		if ($eventsExt === NULL) {
642
			throw new Nette\Utils\AssertionException('Please register the required Kdyby\Events\DI\EventsExtension to Compiler.');
643
		}
644
645
		$this->processRepositories();
646
	}
647
648
649
650
	protected function processRepositories()
651
	{
652
		$builder = $this->getContainerBuilder();
653
654
		$disabled = TRUE;
655
		foreach ($this->configuredManagers as $managerName => $_) {
656
			$factoryClassName = $builder->getDefinition($this->prefix($managerName . '.repositoryFactory'))->class;
657
			if ($factoryClassName === 'Kdyby\Doctrine\RepositoryFactory' || in_array('Kdyby\Doctrine\RepositoryFactory', class_parents($factoryClassName), TRUE)) {
658
				$disabled = FALSE;
659
			}
660
		}
661
662
		if ($disabled) {
663
			return;
664
		}
665
666
		if (!method_exists($builder, 'findByType')) {
667
			foreach ($this->configuredManagers as $managerName => $_) {
668
				$builder->getDefinition($this->prefix($managerName . '.repositoryFactory'))
669
					->addSetup('setServiceIdsMap', [[], $this->prefix('repositoryFactory.' . $managerName . '.defaultRepositoryFactory')]);
670
			}
671
672
			return;
673
		}
674
675
		$serviceMap = array_fill_keys(array_keys($this->configuredManagers), []);
676
		foreach ($builder->findByType('Doctrine\ORM\EntityRepository', FALSE) as $originalServiceName => $originalDef) {
0 ignored issues
show
Unused Code introduced by
The call to ContainerBuilder::findByType() has too many arguments starting with FALSE.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
677
			if (is_string($originalDef)) {
678
				$originalServiceName = $originalDef;
679
				$originalDef = $builder->getDefinition($originalServiceName);
680
			}
681
682
			if (strpos($originalServiceName, $this->name . '.') === 0) {
683
				continue; // ignore
684
			}
685
686
			$factory = $originalDef->getFactory() ? $originalDef->getFactory()->getEntity() : $originalDef->getClass();
687
			if (stripos($factory, '::getRepository') !== FALSE) {
688
				continue; // ignore
689
			}
690
691
			$factoryServiceName = $this->prefix('repositoryFactory.' . $originalServiceName);
692
			$factoryDef = $builder->addDefinition($factoryServiceName, $originalDef)
693
				->setImplement('Kdyby\Doctrine\DI\IRepositoryFactory')
694
				->setParameters(['Doctrine\ORM\EntityManagerInterface entityManager', 'Doctrine\ORM\Mapping\ClassMetadata classMetadata'])
695
				->setAutowired(FALSE);
696
			$factoryStatement = $factoryDef->getFactory() ?: new Statement($factoryDef->getClass());
697
			$factoryStatement->arguments[0] = new Code\PhpLiteral('$entityManager');
698
			$factoryStatement->arguments[1] = new Code\PhpLiteral('$classMetadata');
699
			$factoryDef->setArguments($factoryStatement->arguments);
700
701
			$boundManagers = $this->getServiceBoundManagers($originalDef);
702
			Validators::assert($boundManagers, 'list:1', 'bound manager');
703
704
			if ($boundEntity = $originalDef->getTag(self::TAG_REPOSITORY_ENTITY)) {
705
				if (!is_string($boundEntity) || !class_exists($boundEntity)) {
706
					throw new Nette\Utils\AssertionException(sprintf('The entity "%s" for repository "%s" cannot be autoloaded.', $boundEntity, $originalDef->class));
707
				}
708
				$entityArgument = $boundEntity;
709
710
			} else {
711
				$entityArgument = new Code\PhpLiteral('"%entityName%"');
712
				$this->postCompileRepositoriesQueue[$boundManagers[0]][] = [ltrim($originalDef->class, '\\'), $originalServiceName];
713
			}
714
715
			$builder->removeDefinition($originalServiceName);
716
			$builder->addDefinition($originalServiceName)
717
				->setClass($originalDef->class)
718
				->setFactory(sprintf('@%s::getRepository', $this->configuredManagers[$boundManagers[0]]), [$entityArgument]);
719
720
			$serviceMap[$boundManagers[0]][$originalDef->class] = $factoryServiceName;
721
		}
722
723
		foreach ($this->configuredManagers as $managerName => $_) {
724
			$builder->getDefinition($this->prefix($managerName . '.repositoryFactory'))
725
				->addSetup('setServiceIdsMap', [
726
					$serviceMap[$managerName],
727
					$this->prefix('repositoryFactory.' . $managerName . '.defaultRepositoryFactory')
728
				]);
729
		}
730
	}
731
732
733
734
	/**
735
	 * @param Nette\DI\ServiceDefinition $def
736
	 * @return string[]
737
	 */
738
	protected function getServiceBoundManagers(Nette\DI\ServiceDefinition $def)
739
	{
740
		$builder = $this->getContainerBuilder();
741
		$boundManagers = $def->getTag(self::TAG_BIND_TO_MANAGER);
742
743
		return is_array($boundManagers) ? $boundManagers : [$builder->parameters[$this->name]['orm']['defaultEntityManager']];
744
	}
745
746
747
748
	public function afterCompile(Code\ClassType $class)
749
	{
750
		if ($this->isTracyPresent()) {
751
			$init = $class->methods['initialize'];
752
			$init->addBody('Kdyby\Doctrine\Diagnostics\Panel::registerBluescreen($this);');
753
			$this->addCollapsePathsToTracy($init);
754
		}
755
756
		$this->processRepositoryFactoryEntities($class);
757
	}
758
759
760
761
	protected function processRepositoryFactoryEntities(Code\ClassType $class)
762
	{
763
		if (empty($this->postCompileRepositoriesQueue)) {
764
			return;
765
		}
766
767
		$dic = self::evalAndInstantiateContainer($class);
768
769
		foreach ($this->postCompileRepositoriesQueue as $manager => $items) {
770
			$config = $this->managerConfigs[$manager];
771
			/** @var Kdyby\Doctrine\EntityManager $entityManager */
772
			$entityManager = $dic->getService($this->configuredManagers[$manager]);
773
			/** @var Doctrine\ORM\Mapping\ClassMetadata $entityMetadata */
774
			$metadataFactory = $entityManager->getMetadataFactory();
775
776
			$allMetadata = [];
777
			foreach ($metadataFactory->getAllMetadata() as $entityMetadata) {
778
				if ($config['defaultRepositoryClassName'] === $entityMetadata->customRepositoryClassName || empty($entityMetadata->customRepositoryClassName)) {
779
					continue;
780
				}
781
782
				$allMetadata[ltrim($entityMetadata->customRepositoryClassName, '\\')] = $entityMetadata;
783
			}
784
785
			foreach ($items as $item) {
786
				if (!isset($allMetadata[$item[0]])) {
787
					throw new Nette\Utils\AssertionException(sprintf('Repository class %s have been found in DIC, but no entity has it assigned and it has no entity configured', $item[0]));
788
				}
789
790
				$entityMetadata = $allMetadata[$item[0]];
791
				$serviceMethod = Nette\DI\Container::getMethodName($item[1]);
792
793
				$method = $class->getMethod($serviceMethod);
794
				$methodBody = $method->getBody();
795
				$method->setBody(str_replace('"%entityName%"', Code\Helpers::format('?', $entityMetadata->getName()), $methodBody));
796
			}
797
		}
798
799
		$init = $class->methods['initialize'];
800
		foreach ($this->proxyAutoloaders as $namespace => $dir) {
801
			$originalInitialize = $init->getBody();
802
			$init->setBody('Kdyby\Doctrine\Proxy\ProxyAutoloader::create(?, ?)->register();', array($dir, $namespace));
803
			$init->addBody($originalInitialize);
804
		}
805
	}
806
807
808
809
	/**
810
	 * @param Code\ClassType $class
811
	 * @return Nette\DI\Container
812
	 */
813
	private static function evalAndInstantiateContainer(Code\ClassType $class)
814
	{
815
		$classCopy = clone $class;
816
		$classCopy->setName($className = 'Kdyby_Doctrine_IamTheKingOfHackingNette_' . $class->getName() . '_' . rand());
0 ignored issues
show
Deprecated Code introduced by
The method Nette\PhpGenerator\ClassType::setName() has been deprecated.

This method has been deprecated.

Loading history...
817
818
		$containerCode = "$classCopy";
819
820
		return call_user_func(function () use ($className, $containerCode) {
821
			eval($containerCode);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
822
			return new $className();
823
		});
824
	}
825
826
827
828
	/**
829
	 * @param $provided
830
	 * @param $defaults
831
	 * @param $diff
832
	 * @return array
833
	 */
834
	private function resolveConfig(array $provided, array $defaults, array $diff = [])
835
	{
836
		return $this->getContainerBuilder()->expand(Nette\DI\Config\Helpers::merge(
0 ignored issues
show
Deprecated Code introduced by
The method Nette\DI\ContainerBuilder::expand() has been deprecated.

This method has been deprecated.

Loading history...
837
			array_diff_key($provided, array_diff_key($diff, $defaults)),
838
			$defaults
839
		));
840
	}
841
842
843
	/**
844
	 * @param array $targetEntityMappings
845
	 * @return array
846
	 */
847
	private function normalizeTargetEntityMappings(array $targetEntityMappings)
848
	{
849
		$normalized = [];
850
		foreach ($targetEntityMappings as $originalEntity => $targetEntity) {
851
			$originalEntity = ltrim($originalEntity, '\\');
852
			Validators::assert($targetEntity, 'array|string');
853
			if (is_array($targetEntity)) {
854
				Validators::assertField($targetEntity, 'targetEntity', 'string');
855
				$mapping = array_merge($targetEntity, [
856
					'targetEntity' => ltrim($targetEntity['targetEntity'], '\\')
857
				]);
858
859
			} else {
860
				$mapping = [
861
					'targetEntity' => ltrim($targetEntity, '\\'),
862
				];
863
			}
864
			$normalized[$originalEntity] = $mapping;
865
		}
866
		return $normalized;
867
	}
868
869
870
871
	/**
872
	 * @return bool
873
	 */
874
	private function isTracyPresent()
875
	{
876
		return interface_exists('Tracy\IBarPanel');
877
	}
878
879
880
881
	private function addCollapsePathsToTracy(Method $init)
882
	{
883
		$blueScreen = 'Tracy\Debugger::getBlueScreen()';
884
		$commonDirname = dirname(Nette\Reflection\ClassType::from('Doctrine\Common\Version')->getFileName());
885
886
		$init->addBody($blueScreen . '->collapsePaths[] = ?;', [dirname(Nette\Reflection\ClassType::from('Kdyby\Doctrine\Exception')->getFileName())]);
887
		$init->addBody($blueScreen . '->collapsePaths[] = ?;', [dirname(dirname(dirname(dirname($commonDirname))))]); // this should be vendor/doctrine
888
		foreach ($this->proxyAutoloaders as $dir) {
889
			$init->addBody($blueScreen . '->collapsePaths[] = ?;', [$dir]);
890
		}
891
	}
892
893
894
895
	/**
896
	 * @param \Nette\Configurator $configurator
897
	 */
898
	public static function register(Nette\Configurator $configurator)
899
	{
900
		$configurator->onCompile[] = function ($config, Nette\DI\Compiler $compiler) {
901
			$compiler->addExtension('doctrine', new OrmExtension());
902
		};
903
	}
904
905
906
907
	/**
908
	 * @param array $array
909
	 */
910
	private static function natSortKeys(array &$array)
911
	{
912
		$keys = array_keys($array);
913
		natsort($keys);
914
		$keys = array_flip(array_reverse($keys, TRUE));
915
		$array = array_merge($keys, $array);
916
		return $array;
917
	}
918
919
}
920