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

MongoDBBuilder::getPersistentCollectionNamespace()   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 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\Proxy\AbstractProxyFactory;
16
use Doctrine\MongoDB\Connection;
17
use Doctrine\ODM\MongoDB\Configuration;
18
use Doctrine\ODM\MongoDB\DocumentManager;
19
use Doctrine\ODM\MongoDB\DocumentRepository;
20
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
21
use Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver;
22
use Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver;
23
use Doctrine\ODM\MongoDB\Repository\RepositoryFactory;
24
use Doctrine\ODM\MongoDB\Tools\Console\Helper\DocumentManagerHelper;
25
use Symfony\Component\Console\Command\Command;
26
use Symfony\Component\Console\Helper\HelperSet;
27
28
/**
29
 * Doctrine MongoDB Document Manager builder.
30
 */
31
class MongoDBBuilder extends AbstractManagerBuilder
32
{
33
    /**
34
     * Logger callable.
35
     *
36
     * @var callable
37
     */
38
    protected $loggerCallable;
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected function getDefaultOptions()
44
    {
45
        return [
46
            'connection' => [], // Array or \Doctrine\MongoDB\Connection
47
            'proxies_namespace' => 'DoctrineMongoDBODMProxy',
48
            'metadata_cache_namespace' => 'DoctrineMongoDBODMMetadataCache',
49
            'default_repository_class' => DocumentRepository::class,
50
            'hydrators_namespace' => 'DoctrineMongoDBODMHydrator',
51
            'hydrators_auto_generation' => AbstractProxyFactory::AUTOGENERATE_NEVER,
52
            'persistent_collections_namespace' => 'DoctrineMongoDBODMPersistentCollection',
53
            'persistent_collections_auto_generation' => AbstractProxyFactory::AUTOGENERATE_NEVER,
54
        ];
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    protected function wipe()
61
    {
62
        $this->manager = null;
63
        $this->mappingDriver = null;
64
        $this->metadataCacheDriver = null;
65
        $this->eventManager = null;
66
        $this->loggerCallable = null;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     *
72
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
73
     * @throws \InvalidArgumentException
74
     * @throws \RuntimeException
75
     * @throws \UnexpectedValueException
76
     *
77
     * @return DocumentManager
78
     */
79
    protected function buildManager()
80
    {
81
        $config = new Configuration;
82
83
        $this->setUpGeneralConfigurations($config);
84
        $this->setUpSpecificConfigurations($config);
85
86
        $eventManager = $this->getEventManager();
87
        if ($this->getEventSubscribers() !== null) {
88
            /* @var array $eventSubscribers */
89
            $eventSubscribers = $this->getEventSubscribers();
90
91
            foreach ($eventSubscribers as $eventSubscriber) {
92
                $eventManager->addEventSubscriber($eventSubscriber);
93
            }
94
        }
95
96
        return DocumentManager::create($this->getConnection($config), $config, $eventManager);
97
    }
98
99
    /**
100
     * Set up general manager configurations.
101
     *
102
     * @param Configuration $config
103
     */
104
    protected function setUpGeneralConfigurations(Configuration $config)
105
    {
106
        $this->setupAnnotationMetadata();
107
        $config->setMetadataDriverImpl($this->getMetadataMappingDriver());
108
109
        $config->setProxyDir($this->getProxiesPath());
110
        $config->setProxyNamespace($this->getProxiesNamespace());
111
        $config->setAutoGenerateProxyClasses($this->getProxiesAutoGeneration());
112
113
        if ($this->getRepositoryFactory() !== null) {
114
            $config->setRepositoryFactory($this->getRepositoryFactory());
115
        }
116
117
        if ($this->getDefaultRepositoryClass() !== null) {
118
            $config->setDefaultRepositoryClassName($this->getDefaultRepositoryClass());
119
        }
120
121
        $config->setMetadataCacheImpl($this->getMetadataCacheDriver());
122
    }
123
124
    /**
125
     * Set up manager specific configurations.
126
     *
127
     * @param Configuration $config
128
     */
129
    protected function setUpSpecificConfigurations(Configuration $config)
130
    {
131
        $config->setHydratorDir($this->getHydratorsPath());
132
        $config->setHydratorNamespace($this->getHydratorsNamespace());
133
        $config->setAutoGenerateHydratorClasses($this->getHydratorsAutoGeneration());
134
135
        $config->setPersistentCollectionDir($this->getPersistentCollectionPath());
136
        $config->setPersistentCollectionNamespace($this->getPersistentCollectionNamespace());
137
        $config->setAutoGeneratePersistentCollectionClasses($this->getAutoGeneratePersistentCollection());
138
139
        if ($this->getDefaultDatabase() !== null) {
140
            $config->setDefaultDB($this->getDefaultDatabase());
141
        }
142
143
        if ($this->getLoggerCallable() !== null) {
144
            $config->setLoggerCallable($this->getLoggerCallable());
145
        }
146
147
        foreach ($this->getCustomFilters() as $name => $filterClass) {
148
            $config->addFilter($name, $filterClass);
149
        }
150
    }
151
152
    /**
153
     * Create MongoDB Connection.
154
     *
155
     * @param Configuration $config
156
     *
157
     * @throws \InvalidArgumentException
158
     * @throws \RuntimeException
159
     *
160
     * @return Connection
161
     */
162
    protected function getConnection(Configuration $config)
163
    {
164
        $connection = $this->getOption('connection');
165
166
        switch (true) {
167
            case is_array($connection):
168
                $connection = new Connection(
169
                    array_key_exists('server', $connection) ? $connection['server'] : null,
170
                    array_key_exists('options', $connection) ? $connection['options'] : [],
171
                    $config,
172
                    $this->getEventManager()
173
                );
174
                break;
175
176
            case $connection instanceof Connection:
177
                if ($connection->getEventManager() !== $this->getEventManager()) {
178
                    throw new \RuntimeException(
179
                        'Cannot use different EventManager instances for DocumentManager and Connection.'
180
                    );
181
                }
182
                break;
183
184
            default:
185
                throw new \InvalidArgumentException('Invalid argument: ' . $connection);
186
        }
187
188
        return $connection;
189
    }
190
191
    /**
192
     * {@inheritdoc}
193
     */
194
    protected function getAnnotationMappingDriver(array $paths)
195
    {
196
        return new AnnotationDriver(new AnnotationReader, $paths);
197
    }
198
199
    /**
200
     * {@inheritdoc}
201
     */
202
    protected function getXmlMappingDriver(array $paths, $extension = null)
203
    {
204
        $extension = $extension ?: XmlDriver::DEFAULT_FILE_EXTENSION;
205
206
        return new XmlDriver($paths, $extension);
207
    }
208
209
    /**
210
     * {@inheritdoc}
211
     */
212
    protected function getYamlMappingDriver(array $paths, $extension = null)
213
    {
214
        $extension = $extension ?: YamlDriver::DEFAULT_FILE_EXTENSION;
215
216
        return new YamlDriver($paths, $extension);
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     *
222
     * @throws \InvalidArgumentException
223
     *
224
     * @return RepositoryFactory|null
225
     */
226
    protected function getRepositoryFactory()
227
    {
228
        if (!array_key_exists('repository_factory', $this->options)) {
229
            return;
230
        }
231
232
        $repositoryFactory = $this->options['repository_factory'];
233
234
        if (!$repositoryFactory instanceof RepositoryFactory) {
235
            throw new \InvalidArgumentException(sprintf(
236
                'Invalid factory class "%s". It must be a Doctrine\ODM\MongoDB\Repository\RepositoryFactory.',
237
                get_class($repositoryFactory)
238
            ));
239
        }
240
241
        return $repositoryFactory;
242
    }
243
244
    /**
245
     * Retrieve hydrators path.
246
     *
247
     * @return string
248
     */
249
    protected function getHydratorsPath()
250
    {
251
        return (string) $this->getOption('hydrators_path', sys_get_temp_dir());
252
    }
253
254
    /**
255
     * Retrieve hydrators namespace.
256
     *
257
     * @return null|string
258
     */
259
    protected function getHydratorsNamespace()
260
    {
261
        $proxyNamespace = $this->getOption('hydrators_namespace');
262
263
        return is_string($proxyNamespace) ? $proxyNamespace : null;
264
    }
265
266
    /**
267
     * Retrieve hydrators generation strategy.
268
     *
269
     * @return int
270
     */
271
    protected function getHydratorsAutoGeneration()
272
    {
273
        return (int) $this->getOption('hydrators_auto_generation');
274
    }
275
276
    /**
277
     * Retrieve persistent collections path.
278
     *
279
     * @return string
280
     */
281
    protected function getPersistentCollectionPath()
282
    {
283
        return (string) $this->getOption('persistent_collections_path', sys_get_temp_dir());
284
    }
285
286
    /**
287
     * Retrieve persistent collections namespace.
288
     *
289
     * @return null|string
290
     */
291
    protected function getPersistentCollectionNamespace()
292
    {
293
        $collectionNamespace = $this->getOption('persistent_collections_namespace');
294
295
        return is_string($collectionNamespace) ? $collectionNamespace : null;
296
    }
297
298
    /**
299
     * Retrieve persistent collections generation strategy.
300
     *
301
     * @return int
302
     */
303
    protected function getAutoGeneratePersistentCollection()
304
    {
305
        return (int) $this->getOption('persistent_collections_auto_generation');
306
    }
307
308
    /**
309
     * Get default database.
310
     *
311
     * @return string|null
312
     */
313
    protected function getDefaultDatabase()
314
    {
315
        return $this->hasOption('default_database') ? (string) $this->getOption('default_database') : null;
316
    }
317
318
    /**
319
     * Retrieve logger callable.
320
     *
321
     * @return callable|null
322
     */
323
    protected function getLoggerCallable()
324
    {
325
        if (!is_callable($this->loggerCallable)) {
326
            $loggerCallable = $this->getOption('logger_callable');
327
328
            if (is_callable($loggerCallable)) {
329
                $this->loggerCallable = $loggerCallable;
330
            }
331
        }
332
333
        return $this->loggerCallable;
334
    }
335
336
    /**
337
     * Get custom registered filters.
338
     *
339
     * @return array
340
     */
341
    protected function getCustomFilters()
342
    {
343
        $filters = (array) $this->getOption('custom_filters');
344
345
        return array_filter(
346
            $filters,
347
            function ($name) {
348
                return is_string($name);
349
            },
350
            ARRAY_FILTER_USE_KEY
351
        );
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     *
357
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
358
     * @throws \InvalidArgumentException
359
     * @throws \RuntimeException
360
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
361
     * @throws \Symfony\Component\Console\Exception\LogicException
362
     * @throws \UnexpectedValueException
363
     *
364
     * @return Command[]
365
     */
366
    public function getConsoleCommands()
367
    {
368
        $commands = [
369
            // ODM
370
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateDocumentsCommand,
371
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand,
372
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand,
373
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateRepositoriesCommand,
374
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand,
375
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\ClearCache\MetadataCommand,
376
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand,
377
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand,
378
            new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\UpdateCommand,
379
        ];
380
        $commandPrefix = (string) $this->getName();
381
382
        if ($commandPrefix !== '') {
383
            $commands = array_map(
384
                function (Command $command) use ($commandPrefix) {
385
                    $commandNames = array_map(
386
                        function ($commandName) use ($commandPrefix) {
387
                            return preg_replace('/^odm:/', $commandPrefix . ':odm:', $commandName);
388
                        },
389
                        array_merge([$command->getName()], $command->getAliases())
390
                    );
391
392
                    $command->setName(array_shift($commandNames));
393
                    $command->setAliases($commandNames);
394
395
                    return $command;
396
                },
397
                $commands
398
            );
399
        }
400
401
        return $commands;
402
    }
403
404
    /**
405
     * {@inheritdoc}
406
     *
407
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
408
     * @throws \InvalidArgumentException
409
     * @throws \RuntimeException
410
     * @throws \UnexpectedValueException
411
     */
412
    public function getConsoleHelperSet()
413
    {
414
        return new HelperSet([
415
            'dm' => new DocumentManagerHelper($this->getManager()),
0 ignored issues
show
Compatibility introduced by
$this->getManager() of type object<Doctrine\Common\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ODM\MongoDB\DocumentManager>. It seems like you assume a concrete implementation 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...
416
        ]);
417
    }
418
}
419