Completed
Push — master ( 2d575f...4695ab )
by Julián
02:36
created

RelationalBuilder::getCustomDateTimeFunctions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
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' => 'DoctrineRDBMSORMProxy',
92
            'proxies_auto_generation' => AbstractProxyFactory::AUTOGENERATE_NEVER,
93
            //'cache_driver' => null,
94
            'cache_namespace' => 'DoctrineRDBMSORMCache',
95
            //'metadata_cache_driver' => null,
96
            'metadata_cache_namespace' => 'DoctrineRDBMSORMMetadataCache',
97
            //'query_cache_driver' => null,
98
            'query_cache_namespace' => 'DoctrineRDBMSORMQueryCache',
99
            //'result_cache_driver' => null,
100
            'result_cache_namespace' => 'DoctrineRDBMSORMResultCache',
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
     * Get default repository class name
327
     *
328
     * @return string|null
329
     */
330
    protected function getDefaultRepositoryClass()
331
    {
332
        return array_key_exists('default_repository_class', $this->options)
333
            ? (string) $this->options['default_repository_class']
334
            : null;
335
    }
336
337
    /**
338
     * Retrieve naming strategy.
339
     *
340
     * @return NamingStrategy
341
     */
342
    protected function getNamingStrategy()
343
    {
344
        if (!$this->namingStrategy instanceof NamingStrategy) {
345
            $namingStrategy = $this->getOption('naming_strategy');
346
347
            if (!$namingStrategy instanceof NamingStrategy) {
348
                $namingStrategy = new UnderscoreNamingStrategy(CASE_LOWER);
349
            }
350
351
            $this->namingStrategy = $namingStrategy;
352
        }
353
354
        return $this->namingStrategy;
355
    }
356
357
    /**
358
     * Retrieve quote strategy.
359
     *
360
     * @throws \InvalidArgumentException
361
     *
362
     * @return QuoteStrategy
363
     */
364
    protected function getQuoteStrategy()
365
    {
366
        if (!$this->quoteStrategy instanceof QuoteStrategy) {
367
            $quoteStrategy = $this->getOption('quote_strategy');
368
369
            if (!$quoteStrategy instanceof QuoteStrategy) {
370
                $quoteStrategy = new DefaultQuoteStrategy;
371
            }
372
373
            $this->quoteStrategy = $quoteStrategy;
374
        }
375
376
        return $this->quoteStrategy;
377
    }
378
379
    /**
380
     * Retrieve SQL logger.
381
     *
382
     * @return SQLLogger|null
383
     */
384
    protected function getSQLLogger()
385
    {
386
        if (!$this->SQLLogger instanceof SQLLogger) {
387
            $sqlLogger = $this->getOption('sql_logger');
388
389
            if ($sqlLogger instanceof SQLLogger) {
390
                $this->SQLLogger = $sqlLogger;
391
            }
392
        }
393
394
        return $this->SQLLogger;
395
    }
396
397
    /**
398
     * Retrieve custom DQL string functions.
399
     *
400
     * @return array
401
     */
402
    protected function getCustomStringFunctions()
403
    {
404
        $functions = (array) $this->getOption('custom_string_functions');
405
406
        return array_filter(
407
            $functions,
408
            function ($name) {
409
                return is_string($name);
410
            },
411
            ARRAY_FILTER_USE_KEY
412
        );
413
    }
414
415
    /**
416
     * Retrieve custom DQL numeric functions.
417
     *
418
     * @return array
419
     */
420
    protected function getCustomNumericFunctions()
421
    {
422
        $functions = (array) $this->getOption('custom_numeric_functions');
423
424
        return array_filter(
425
            $functions,
426
            function ($name) {
427
                return is_string($name);
428
            },
429
            ARRAY_FILTER_USE_KEY
430
        );
431
    }
432
433
    /**
434
     * Retrieve custom DQL date time functions.
435
     *
436
     * @return array
437
     */
438
    protected function getCustomDateTimeFunctions()
439
    {
440
        $functions = (array) $this->getOption('custom_datetime_functions');
441
442
        return array_filter(
443
            $functions,
444
            function ($name) {
445
                return is_string($name);
446
            },
447
            ARRAY_FILTER_USE_KEY
448
        );
449
    }
450
451
    /**
452
     * Retrieve custom DBAL types.
453
     *
454
     * @return array
455
     */
456
    protected function getCustomTypes()
457
    {
458
        $types = (array) $this->getOption('custom_types');
459
460
        return array_filter(
461
            $types,
462
            function ($name) {
463
                return is_string($name);
464
            },
465
            ARRAY_FILTER_USE_KEY
466
        );
467
    }
468
469
    /**
470
     * {@inheritdoc}
471
     *
472
     * @throws \Doctrine\DBAL\DBALException
473
     * @throws \Doctrine\ORM\ORMException
474
     * @throws \InvalidArgumentException
475
     * @throws \RuntimeException
476
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
477
     * @throws \Symfony\Component\Console\Exception\LogicException
478
     * @throws \UnexpectedValueException
479
     *
480
     * @return Command[]
481
     */
482
    public function getConsoleCommands()
483
    {
484
        $commands = [
485
            // DBAL
486
            new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
487
            new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
488
489
            // ORM
490
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
491
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
492
            new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
493
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
494
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
495
            new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
496
            new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
497
            new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
498
            new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
499
            new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
500
            new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
501
            new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
502
            new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
503
            new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
504
            new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
505
            new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand(),
506
        ];
507
        $commandPrefix = (string) $this->getName();
508
509
        if ($commandPrefix !== '') {
510
            $commands = array_map(
511
                function (Command $command) use ($commandPrefix) {
512
                    $commandNames = array_map(
513
                        function ($commandName) use ($commandPrefix) {
514
                            return preg_replace('/^(dbal|orm):/', $commandPrefix . ':$1:', $commandName);
515
                        },
516
                        array_merge([$command->getName()], $command->getAliases())
517
                    );
518
519
                    $command->setName(array_shift($commandNames));
520
                    $command->setAliases($commandNames);
521
522
                    return $command;
523
                },
524
                $commands
525
            );
526
        }
527
528
        return $commands;
529
    }
530
531
    /**
532
     * {@inheritdoc}
533
     *
534
     * @throws \Doctrine\DBAL\DBALException
535
     * @throws \Doctrine\ORM\ORMException
536
     * @throws \InvalidArgumentException
537
     * @throws \RuntimeException
538
     * @throws \UnexpectedValueException
539
     */
540
    public function getConsoleHelperSet()
541
    {
542
        $entityManager = $this->getManager();
543
544
        return new HelperSet([
545
            'db' => new ConnectionHelper($entityManager->getConnection()),
546
            'em' => new EntityManagerHelper($entityManager),
547
        ]);
548
    }
549
}
550