Completed
Push — master ( 7e6b75...39b5c8 )
by Julián
02:19
created

RelationalBuilder::getXmlMappingDriver()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
/*
4
 * doctrine-manager-builder (https://github.com/juliangut/doctrine-manager-builder).
5
 * Doctrine2 managers builder.
6
 *
7
 * @license BSD-3-Clause
8
 * @link https://github.com/juliangut/doctrine-manager-builder
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
namespace Jgut\Doctrine\ManagerBuilder;
13
14
use Doctrine\Common\Annotations\AnnotationReader;
15
use Doctrine\Common\Cache\CacheProvider;
16
use Doctrine\DBAL\Logging\SQLLogger;
17
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
18
use Doctrine\DBAL\Types\Type;
19
use Doctrine\ORM\Configuration;
20
use Doctrine\ORM\EntityManager;
21
use Doctrine\ORM\EntityRepository;
22
use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
23
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
24
use Doctrine\ORM\Mapping\Driver\XmlDriver;
25
use Doctrine\ORM\Mapping\Driver\YamlDriver;
26
use Doctrine\ORM\Mapping\NamingStrategy;
27
use Doctrine\ORM\Mapping\QuoteStrategy;
28
use Doctrine\ORM\Mapping\UnderscoreNamingStrategy;
29
use Doctrine\ORM\Repository\RepositoryFactory;
30
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
31
use Doctrine\ORM\Version;
32
use Symfony\Component\Console\Command\Command;
33
use Symfony\Component\Console\Helper\HelperSet;
34
35
/**
36
 * Doctrine RDBMS Entity Manager builder.
37
 */
38
class RelationalBuilder extends AbstractManagerBuilder
39
{
40
    /**
41
     * Entity Manager.
42
     *
43
     * @var EntityManager
44
     */
45
    protected $manager;
46
47
    /**
48
     * Query cache driver.
49
     *
50
     * @var CacheProvider
51
     */
52
    protected $queryCacheDriver;
53
54
    /**
55
     * Result cache driver.
56
     *
57
     * @var CacheProvider
58
     */
59
    protected $resultCacheDriver;
60
61
    /**
62
     * Naming strategy.
63
     *
64
     * @var NamingStrategy
65
     */
66
    protected $namingStrategy;
67
68
    /**
69
     * Quote strategy.
70
     *
71
     * @var QuoteStrategy
72
     */
73
    protected $quoteStrategy;
74
75
    /**
76
     * SQL logger.
77
     *
78
     * @var SQLLogger
79
     */
80
    protected $SQLLogger;
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    protected function getDefaultOptions()
86
    {
87
        return [
88
            'connection' => [], // Array or \Doctrine\DBAL\Connection
89
            'proxies_namespace' => 'DoctrineRDBMSORMProxy',
90
            'metadata_cache_namespace' => 'DoctrineRDBMSORMMetadataCache',
91
            'query_cache_namespace' => 'DoctrineRDBMSORMQueryCache',
92
            'result_cache_namespace' => 'DoctrineRDBMSORMResultCache',
93
            'default_repository_class' => EntityRepository::class,
94
        ];
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     *
100
     * @throws \Doctrine\DBAL\DBALException
101
     * @throws \Doctrine\ORM\ORMException
102
     * @throws \InvalidArgumentException
103
     * @throws \RuntimeException
104
     * @throws \UnexpectedValueException
105
     *
106
     * @return EntityManager
107
     */
108
    public function getManager($force = false)
109
    {
110
        if ($force === true) {
111
            $this->wipe();
112
        }
113
114
        if (!$this->manager instanceof EntityManager) {
115
            $this->manager = $this->buildManager();
116
        }
117
118
        return $this->manager;
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    protected function wipe()
125
    {
126
        parent::wipe();
127
128
        $this->manager = null;
129
        $this->queryCacheDriver = null;
130
        $this->resultCacheDriver = null;
131
        $this->namingStrategy = null;
132
        $this->quoteStrategy = null;
133
        $this->SQLLogger = null;
134
    }
135
136
    /**
137
     * Build new Doctrine entity manager.
138
     *
139
     * @throws \Doctrine\DBAL\DBALException
140
     * @throws \Doctrine\ORM\ORMException
141
     * @throws \InvalidArgumentException
142
     * @throws \RuntimeException
143
     * @throws \UnexpectedValueException
144
     *
145
     * @return EntityManager
146
     */
147
    protected function buildManager()
148
    {
149
        $config = new Configuration();
150
151
        $this->setUpGeneralConfigurations($config);
152
        $this->setUpSpecificConfigurations($config);
153
154
        $eventManager = $this->getEventManager();
155
        if ($this->getEventSubscribers() !== null) {
156
            /* @var array $eventSubscribers */
157
            $eventSubscribers = $this->getEventSubscribers();
158
159
            foreach ($eventSubscribers as $eventSubscriber) {
160
                $eventManager->addEventSubscriber($eventSubscriber);
161
            }
162
        }
163
164
        $entityManager = EntityManager::create($this->getOption('connection'), $config, $eventManager);
165
166
        $platform = $entityManager->getConnection()->getDatabasePlatform();
167
        foreach ($this->getCustomTypes() as $type => $class) {
168
            Type::addType($type, $class);
169
            $platform->registerDoctrineTypeMapping($type, $type);
170
        }
171
172
        return $entityManager;
173
    }
174
175
    /**
176
     * Set up general manager configurations.
177
     *
178
     * @param Configuration $config
179
     */
180
    protected function setUpGeneralConfigurations(Configuration $config)
181
    {
182
        $this->setupAnnotationMetadata();
183
        $config->setMetadataDriverImpl($this->getMetadataMappingDriver());
184
185
        $config->setProxyDir($this->getProxiesPath());
186
        $config->setProxyNamespace($this->getProxiesNamespace());
187
        $config->setAutoGenerateProxyClasses($this->getProxiesAutoGeneration());
0 ignored issues
show
Documentation introduced by
$this->getProxiesAutoGeneration() is of type integer, 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...
188
189
        if ($this->getRepositoryFactory() !== null) {
190
            $config->setRepositoryFactory($this->getRepositoryFactory());
191
        }
192
193
        if ($this->getDefaultRepositoryClass() !== null) {
194
            $config->setDefaultRepositoryClassName($this->getDefaultRepositoryClass());
195
        }
196
197
        $config->setMetadataCacheImpl($this->getMetadataCacheDriver());
198
    }
199
200
    /**
201
     * Set up manager specific configurations.
202
     *
203
     * @param Configuration $config
204
     */
205
    protected function setUpSpecificConfigurations(Configuration $config)
206
    {
207
        $config->setQueryCacheImpl($this->getQueryCacheDriver());
208
        $config->setResultCacheImpl($this->getResultCacheDriver());
209
210
        $config->setNamingStrategy($this->getNamingStrategy());
211
        $config->setQuoteStrategy($this->getQuoteStrategy());
212
213
        $config->setSQLLogger($this->getSQLLogger());
214
        $config->setCustomStringFunctions($this->getCustomStringFunctions());
215
        $config->setCustomNumericFunctions($this->getCustomNumericFunctions());
216
        $config->setCustomDatetimeFunctions($this->getCustomDateTimeFunctions());
217
218
        foreach ($this->getCustomFilters() as $name => $filterClass) {
219
            $config->addFilter($name, $filterClass);
220
        }
221
    }
222
223
    /**
224
     * {@inheritdoc}
225
     */
226
    protected function getAnnotationMappingDriver(array $paths)
227
    {
228
        return new AnnotationDriver(new AnnotationReader, $paths);
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     */
234
    protected function getXmlMappingDriver(array $paths, $extension = null)
235
    {
236
        $extension = $extension ?: XmlDriver::DEFAULT_FILE_EXTENSION;
237
238
        return new XmlDriver($paths, $extension);
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244
    protected function getYamlMappingDriver(array $paths, $extension = null)
245
    {
246
        $extension = $extension ?: YamlDriver::DEFAULT_FILE_EXTENSION;
247
248
        return new YamlDriver($paths, $extension);
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     *
254
     * @throws \InvalidArgumentException
255
     *
256
     * @return RepositoryFactory|null
257
     */
258
    protected function getRepositoryFactory()
259
    {
260
        if (!array_key_exists('repository_factory', $this->options)) {
261
            return;
262
        }
263
264
        $repositoryFactory = $this->options['repository_factory'];
265
266
        if (!$repositoryFactory instanceof RepositoryFactory) {
267
            throw new \InvalidArgumentException(sprintf(
268
                'Invalid factory class "%s". It must be a Doctrine\ORM\Repository\RepositoryFactory.',
269
                get_class($repositoryFactory)
270
            ));
271
        }
272
273
        return $repositoryFactory;
274
    }
275
276
    /**
277
     * Retrieve query cache driver.
278
     *
279
     * @throws \InvalidArgumentException
280
     *
281
     * @return CacheProvider
282
     */
283
    public function getQueryCacheDriver()
284
    {
285
        if (!$this->queryCacheDriver instanceof CacheProvider) {
286
            $queryCacheDriver = $this->getOption('query_cache_driver');
287
            $cacheNamespace = (string) $this->getOption('query_cache_namespace');
288
289
            if (!$queryCacheDriver instanceof CacheProvider) {
290
                $queryCacheDriver = clone $this->getMetadataCacheDriver();
291
                $queryCacheDriver->setNamespace($cacheNamespace);
292
            }
293
294
            if ($queryCacheDriver->getNamespace() === '') {
295
                $queryCacheDriver->setNamespace($cacheNamespace);
296
            }
297
298
            $this->queryCacheDriver = $queryCacheDriver;
299
        }
300
301
        return $this->queryCacheDriver;
302
    }
303
304
    /**
305
     * Set query cache driver.
306
     *
307
     * @param CacheProvider $queryCacheDriver
308
     */
309
    public function setQueryCacheDriver(CacheProvider $queryCacheDriver)
310
    {
311
        $this->queryCacheDriver = $queryCacheDriver;
312
    }
313
314
    /**
315
     * Retrieve result cache driver.
316
     *
317
     * @throws \InvalidArgumentException
318
     *
319
     * @return CacheProvider
320
     */
321
    public function getResultCacheDriver()
322
    {
323
        if (!$this->resultCacheDriver instanceof CacheProvider) {
324
            $resultCacheDriver = $this->getOption('result_cache_driver');
325
            $cacheNamespace = (string) $this->getOption('result_cache_namespace');
326
327
            if (!$resultCacheDriver instanceof CacheProvider) {
328
                $resultCacheDriver = clone $this->getMetadataCacheDriver();
329
                $resultCacheDriver->setNamespace($cacheNamespace);
330
            }
331
332
            if ($resultCacheDriver->getNamespace() === '') {
333
                $resultCacheDriver->setNamespace($cacheNamespace);
334
            }
335
336
            $this->resultCacheDriver = $resultCacheDriver;
337
        }
338
339
        return $this->resultCacheDriver;
340
    }
341
342
    /**
343
     * Set result cache driver.
344
     *
345
     * @param CacheProvider $resultCacheDriver
346
     */
347
    public function setResultCacheDriver(CacheProvider $resultCacheDriver)
348
    {
349
        $this->resultCacheDriver = $resultCacheDriver;
350
    }
351
352
    /**
353
     * Retrieve naming strategy.
354
     *
355
     * @return NamingStrategy
356
     */
357
    protected function getNamingStrategy()
358
    {
359
        if (!$this->namingStrategy instanceof NamingStrategy) {
360
            $namingStrategy = $this->getOption('naming_strategy');
361
362
            if (!$namingStrategy instanceof NamingStrategy) {
363
                $namingStrategy = new UnderscoreNamingStrategy(CASE_LOWER);
364
            }
365
366
            $this->namingStrategy = $namingStrategy;
367
        }
368
369
        return $this->namingStrategy;
370
    }
371
372
    /**
373
     * Retrieve quote strategy.
374
     *
375
     * @throws \InvalidArgumentException
376
     *
377
     * @return QuoteStrategy
378
     */
379
    protected function getQuoteStrategy()
380
    {
381
        if (!$this->quoteStrategy instanceof QuoteStrategy) {
382
            $quoteStrategy = $this->getOption('quote_strategy');
383
384
            if (!$quoteStrategy instanceof QuoteStrategy) {
385
                $quoteStrategy = new DefaultQuoteStrategy;
386
            }
387
388
            $this->quoteStrategy = $quoteStrategy;
389
        }
390
391
        return $this->quoteStrategy;
392
    }
393
394
    /**
395
     * Retrieve SQL logger.
396
     *
397
     * @return SQLLogger|null
398
     */
399
    protected function getSQLLogger()
400
    {
401
        if (!$this->SQLLogger instanceof SQLLogger) {
402
            $sqlLogger = $this->getOption('sql_logger');
403
404
            if ($sqlLogger instanceof SQLLogger) {
405
                $this->SQLLogger = $sqlLogger;
406
            }
407
        }
408
409
        return $this->SQLLogger;
410
    }
411
412
    /**
413
     * Retrieve custom DQL string functions.
414
     *
415
     * @return array
416
     */
417
    protected function getCustomStringFunctions()
418
    {
419
        $functions = (array) $this->getOption('custom_string_functions');
420
421
        return array_filter(
422
            $functions,
423
            function ($name) {
424
                return is_string($name);
425
            },
426
            ARRAY_FILTER_USE_KEY
427
        );
428
    }
429
430
    /**
431
     * Retrieve custom DQL numeric functions.
432
     *
433
     * @return array
434
     */
435
    protected function getCustomNumericFunctions()
436
    {
437
        $functions = (array) $this->getOption('custom_numeric_functions');
438
439
        return array_filter(
440
            $functions,
441
            function ($name) {
442
                return is_string($name);
443
            },
444
            ARRAY_FILTER_USE_KEY
445
        );
446
    }
447
448
    /**
449
     * Retrieve custom DQL date time functions.
450
     *
451
     * @return array
452
     */
453
    protected function getCustomDateTimeFunctions()
454
    {
455
        $functions = (array) $this->getOption('custom_datetime_functions');
456
457
        return array_filter(
458
            $functions,
459
            function ($name) {
460
                return is_string($name);
461
            },
462
            ARRAY_FILTER_USE_KEY
463
        );
464
    }
465
466
    /**
467
     * Retrieve custom DBAL types.
468
     *
469
     * @return array
470
     */
471
    protected function getCustomTypes()
472
    {
473
        $types = (array) $this->getOption('custom_types');
474
475
        return array_filter(
476
            $types,
477
            function ($name) {
478
                return is_string($name);
479
            },
480
            ARRAY_FILTER_USE_KEY
481
        );
482
    }
483
484
    /**
485
     * Get custom registered filters.
486
     *
487
     * @return array
488
     */
489
    protected function getCustomFilters()
490
    {
491
        $filters = (array) $this->getOption('custom_filters');
492
493
        return array_filter(
494
            $filters,
495
            function ($name) {
496
                return is_string($name);
497
            },
498
            ARRAY_FILTER_USE_KEY
499
        );
500
    }
501
502
    /**
503
     * {@inheritdoc}
504
     *
505
     * @throws \Doctrine\DBAL\DBALException
506
     * @throws \Doctrine\ORM\ORMException
507
     * @throws \InvalidArgumentException
508
     * @throws \RuntimeException
509
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
510
     * @throws \Symfony\Component\Console\Exception\LogicException
511
     * @throws \UnexpectedValueException
512
     *
513
     * @return Command[]
514
     */
515
    public function getConsoleCommands()
516
    {
517
        $commands = [
518
            // DBAL
519
            new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
520
            new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
521
522
            // ORM
523
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
524
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
525
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
526
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
527
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
528
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
529
            new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
530
            new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
531
            new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
532
            new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
533
            new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
534
            new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
535
            new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
536
            new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
537
            new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
538
        ];
539
540
        if (Version::compare('2.5') <= 0) {
541
            $commands[] = new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand();
542
        }
543
544
        $commandPrefix = (string) $this->getName();
545
546
        if ($commandPrefix !== '') {
547
            $commands = array_map(
548
                function (Command $command) use ($commandPrefix) {
549
                    $commandNames = array_map(
550
                        function ($commandName) use ($commandPrefix) {
551
                            return preg_replace('/^(dbal|orm):/', $commandPrefix . ':$1:', $commandName);
552
                        },
553
                        array_merge([$command->getName()], $command->getAliases())
554
                    );
555
556
                    $command->setName(array_shift($commandNames));
557
                    $command->setAliases($commandNames);
558
559
                    return $command;
560
                },
561
                $commands
562
            );
563
        }
564
565
        return $commands;
566
    }
567
568
    /**
569
     * {@inheritdoc}
570
     *
571
     * @throws \Doctrine\DBAL\DBALException
572
     * @throws \Doctrine\ORM\ORMException
573
     * @throws \InvalidArgumentException
574
     * @throws \RuntimeException
575
     * @throws \UnexpectedValueException
576
     */
577
    public function getConsoleHelperSet()
578
    {
579
        $entityManager = $this->getManager();
580
581
        return new HelperSet([
582
            'db' => new ConnectionHelper($entityManager->getConnection()),
583
            'em' => new EntityManagerHelper($entityManager),
584
        ]);
585
    }
586
}
587