Completed
Push — master ( b5054b...5e1fc6 )
by Julián
02:29
created

RelationalBuilder::getDefaultOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
554
        ]);
555
    }
556
}
557