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

getAutoGeneratePersistentCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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