Completed
Push — master ( 5c7019...2d575f )
by Julián
03:04
created

RelationalBuilder::getConsoleCommands()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 48
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

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