Completed
Push — master ( d34e64...7e6b75 )
by Julián
06:06
created

RelationalBuilder::getNamingStrategy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 0
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
        if (count($this->getCustomFilters())) {
219
            foreach ($this->getCustomFilters() as $name => $filterClass) {
220
                $config->addFilter($name, $filterClass);
221
            }
222
        }
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228
    protected function getAnnotationMetadataDriver(array $paths)
229
    {
230
        return new AnnotationDriver(new AnnotationReader, $paths);
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    protected function getXmlMetadataDriver(array $paths, $extension = null)
237
    {
238
        $extension = $extension ?: XmlDriver::DEFAULT_FILE_EXTENSION;
239
240
        return new XmlDriver($paths, $extension);
241
    }
242
243
    /**
244
     * {@inheritdoc}
245
     */
246
    protected function getYamlMetadataDriver(array $paths, $extension = null)
247
    {
248
        $extension = $extension ?: YamlDriver::DEFAULT_FILE_EXTENSION;
249
250
        return new YamlDriver($paths, $extension);
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     *
256
     * @throws \InvalidArgumentException
257
     *
258
     * @return RepositoryFactory|null
259
     */
260
    protected function getRepositoryFactory()
261
    {
262
        if (!array_key_exists('repository_factory', $this->options)) {
263
            return;
264
        }
265
266
        $repositoryFactory = $this->options['repository_factory'];
267
268
        if (!$repositoryFactory instanceof RepositoryFactory) {
269
            throw new \InvalidArgumentException(sprintf(
270
                'Invalid factory class "%s". It must be a Doctrine\ORM\Repository\RepositoryFactory.',
271
                get_class($repositoryFactory)
272
            ));
273
        }
274
275
        return $repositoryFactory;
276
    }
277
278
    /**
279
     * Retrieve query cache driver.
280
     *
281
     * @throws \InvalidArgumentException
282
     *
283
     * @return CacheProvider
284
     */
285
    public function getQueryCacheDriver()
286
    {
287
        if (!$this->queryCacheDriver instanceof CacheProvider) {
288
            $queryCacheDriver = $this->getOption('query_cache_driver');
289
            $cacheNamespace = (string) $this->getOption('query_cache_namespace');
290
291
            if (!$queryCacheDriver instanceof CacheProvider) {
292
                $queryCacheDriver = clone $this->getMetadataCacheDriver();
293
                $queryCacheDriver->setNamespace($cacheNamespace);
294
            }
295
296
            if ($queryCacheDriver->getNamespace() === '') {
297
                $queryCacheDriver->setNamespace($cacheNamespace);
298
            }
299
300
            $this->queryCacheDriver = $queryCacheDriver;
301
        }
302
303
        return $this->queryCacheDriver;
304
    }
305
306
    /**
307
     * Set query cache driver.
308
     *
309
     * @param CacheProvider $queryCacheDriver
310
     */
311
    public function setQueryCacheDriver(CacheProvider $queryCacheDriver)
312
    {
313
        $this->queryCacheDriver = $queryCacheDriver;
314
    }
315
316
    /**
317
     * Retrieve result cache driver.
318
     *
319
     * @throws \InvalidArgumentException
320
     *
321
     * @return CacheProvider
322
     */
323
    public function getResultCacheDriver()
324
    {
325
        if (!$this->resultCacheDriver instanceof CacheProvider) {
326
            $resultCacheDriver = $this->getOption('result_cache_driver');
327
            $cacheNamespace = (string) $this->getOption('result_cache_namespace');
328
329
            if (!$resultCacheDriver instanceof CacheProvider) {
330
                $resultCacheDriver = clone $this->getMetadataCacheDriver();
331
                $resultCacheDriver->setNamespace($cacheNamespace);
332
            }
333
334
            if ($resultCacheDriver->getNamespace() === '') {
335
                $resultCacheDriver->setNamespace($cacheNamespace);
336
            }
337
338
            $this->resultCacheDriver = $resultCacheDriver;
339
        }
340
341
        return $this->resultCacheDriver;
342
    }
343
344
    /**
345
     * Set result cache driver.
346
     *
347
     * @param CacheProvider $resultCacheDriver
348
     */
349
    public function setResultCacheDriver(CacheProvider $resultCacheDriver)
350
    {
351
        $this->resultCacheDriver = $resultCacheDriver;
352
    }
353
354
    /**
355
     * Retrieve naming strategy.
356
     *
357
     * @return NamingStrategy
358
     */
359
    protected function getNamingStrategy()
360
    {
361
        if (!$this->namingStrategy instanceof NamingStrategy) {
362
            $namingStrategy = $this->getOption('naming_strategy');
363
364
            if (!$namingStrategy instanceof NamingStrategy) {
365
                $namingStrategy = new UnderscoreNamingStrategy(CASE_LOWER);
366
            }
367
368
            $this->namingStrategy = $namingStrategy;
369
        }
370
371
        return $this->namingStrategy;
372
    }
373
374
    /**
375
     * Retrieve quote strategy.
376
     *
377
     * @throws \InvalidArgumentException
378
     *
379
     * @return QuoteStrategy
380
     */
381
    protected function getQuoteStrategy()
382
    {
383
        if (!$this->quoteStrategy instanceof QuoteStrategy) {
384
            $quoteStrategy = $this->getOption('quote_strategy');
385
386
            if (!$quoteStrategy instanceof QuoteStrategy) {
387
                $quoteStrategy = new DefaultQuoteStrategy;
388
            }
389
390
            $this->quoteStrategy = $quoteStrategy;
391
        }
392
393
        return $this->quoteStrategy;
394
    }
395
396
    /**
397
     * Retrieve SQL logger.
398
     *
399
     * @return SQLLogger|null
400
     */
401
    protected function getSQLLogger()
402
    {
403
        if (!$this->SQLLogger instanceof SQLLogger) {
404
            $sqlLogger = $this->getOption('sql_logger');
405
406
            if ($sqlLogger instanceof SQLLogger) {
407
                $this->SQLLogger = $sqlLogger;
408
            }
409
        }
410
411
        return $this->SQLLogger;
412
    }
413
414
    /**
415
     * Retrieve custom DQL string functions.
416
     *
417
     * @return array
418
     */
419
    protected function getCustomStringFunctions()
420
    {
421
        $functions = (array) $this->getOption('custom_string_functions');
422
423
        return array_filter(
424
            $functions,
425
            function ($name) {
426
                return is_string($name);
427
            },
428
            ARRAY_FILTER_USE_KEY
429
        );
430
    }
431
432
    /**
433
     * Retrieve custom DQL numeric functions.
434
     *
435
     * @return array
436
     */
437
    protected function getCustomNumericFunctions()
438
    {
439
        $functions = (array) $this->getOption('custom_numeric_functions');
440
441
        return array_filter(
442
            $functions,
443
            function ($name) {
444
                return is_string($name);
445
            },
446
            ARRAY_FILTER_USE_KEY
447
        );
448
    }
449
450
    /**
451
     * Retrieve custom DQL date time functions.
452
     *
453
     * @return array
454
     */
455
    protected function getCustomDateTimeFunctions()
456
    {
457
        $functions = (array) $this->getOption('custom_datetime_functions');
458
459
        return array_filter(
460
            $functions,
461
            function ($name) {
462
                return is_string($name);
463
            },
464
            ARRAY_FILTER_USE_KEY
465
        );
466
    }
467
468
    /**
469
     * Retrieve custom DBAL types.
470
     *
471
     * @return array
472
     */
473
    protected function getCustomTypes()
474
    {
475
        $types = (array) $this->getOption('custom_types');
476
477
        return array_filter(
478
            $types,
479
            function ($name) {
480
                return is_string($name);
481
            },
482
            ARRAY_FILTER_USE_KEY
483
        );
484
    }
485
486
    /**
487
     * Get custom registered filters.
488
     *
489
     * @return array
490
     */
491
    protected function getCustomFilters()
492
    {
493
        $filters = (array) $this->getOption('custom_filters');
494
495
        return array_filter(
496
            $filters,
497
            function ($name) {
498
                return is_string($name);
499
            },
500
            ARRAY_FILTER_USE_KEY
501
        );
502
    }
503
504
    /**
505
     * {@inheritdoc}
506
     *
507
     * @throws \Doctrine\DBAL\DBALException
508
     * @throws \Doctrine\ORM\ORMException
509
     * @throws \InvalidArgumentException
510
     * @throws \RuntimeException
511
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
512
     * @throws \Symfony\Component\Console\Exception\LogicException
513
     * @throws \UnexpectedValueException
514
     *
515
     * @return Command[]
516
     */
517
    public function getConsoleCommands()
518
    {
519
        $commands = [
520
            // DBAL
521
            new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
522
            new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
523
524
            // ORM
525
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
526
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
527
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
528
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
529
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
530
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
531
            new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
532
            new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
533
            new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
534
            new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
535
            new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
536
            new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
537
            new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
538
            new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
539
            new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
540
        ];
541
542
        if (Version::compare('2.5') <= 0) {
543
            $commands[] = new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand();
544
        }
545
546
        $commandPrefix = (string) $this->getName();
547
548
        if ($commandPrefix !== '') {
549
            $commands = array_map(
550
                function (Command $command) use ($commandPrefix) {
551
                    $commandNames = array_map(
552
                        function ($commandName) use ($commandPrefix) {
553
                            return preg_replace('/^(dbal|orm):/', $commandPrefix . ':$1:', $commandName);
554
                        },
555
                        array_merge([$command->getName()], $command->getAliases())
556
                    );
557
558
                    $command->setName(array_shift($commandNames));
559
                    $command->setAliases($commandNames);
560
561
                    return $command;
562
                },
563
                $commands
564
            );
565
        }
566
567
        return $commands;
568
    }
569
570
    /**
571
     * {@inheritdoc}
572
     *
573
     * @throws \Doctrine\DBAL\DBALException
574
     * @throws \Doctrine\ORM\ORMException
575
     * @throws \InvalidArgumentException
576
     * @throws \RuntimeException
577
     * @throws \UnexpectedValueException
578
     */
579
    public function getConsoleHelperSet()
580
    {
581
        $entityManager = $this->getManager();
582
583
        return new HelperSet([
584
            'db' => new ConnectionHelper($entityManager->getConnection()),
585
            'em' => new EntityManagerHelper($entityManager),
586
        ]);
587
    }
588
}
589