Completed
Push — master ( 4695ab...73566d )
by Julián
02:31
created

MongoDBBuilder::getDefaultOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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