Completed
Push — master ( b2a456...e36983 )
by Julián
02:34
created

DocumentManagerBuilder::setupMetadataDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
/**
3
 * Slim3 Doctrine integration (https://github.com/juliangut/slim-doctrine)
4
 *
5
 * @link https://github.com/juliangut/slim-doctrine for the canonical source repository
6
 *
7
 * @license https://raw.githubusercontent.com/juliangut/slim-doctrine/master/LICENSE
8
 */
9
10
namespace Jgut\Slim\Doctrine;
11
12
use Doctrine\Common\Annotations\AnnotationReader;
13
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;
14
use Doctrine\Common\Proxy\AbstractProxyFactory;
15
use Doctrine\MongoDB\Connection;
16
use Doctrine\ODM\MongoDB\Configuration;
17
use Doctrine\ODM\MongoDB\DocumentManager;
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
22
/**
23
 * Doctrine Document Manager service builder.
24
 */
25
class DocumentManagerBuilder
26
{
27
    use ObjectManagerTrait;
28
29
    /**
30
     * Default configuration options.
31
     *
32
     * @var array
33
     */
34
    protected static $defaultOptions = [
35
        'connection' => null,
36
        'cache_driver' => null,
37
        'cache_namespace' => null,
38
        'annotation_files' => [],
39
        'annotation_namespaces' => [],
40
        'annotation_autoloaders' => [],
41
        'annotation_paths' => null,
42
        'xml_paths' => null,
43
        'yaml_paths' => null,
44
        'php_paths' => null,
45
        'default_database' => null,
46
        'proxy_path' => null,
47
        'proxies_namespace' => 'DoctrineODMProxy',
48
        'auto_generate_proxies' => AbstractProxyFactory::AUTOGENERATE_NEVER,
49
        'hydrator_path' => null,
50
        'hydrators_namespace' => 'DoctrineODMHydrator',
51
        'auto_generate_hydrators' => AbstractProxyFactory::AUTOGENERATE_NEVER,
52
        'logger_callable' => null,
53
        'event_manager' => null,
54
    ];
55
56
    /**
57
     * Create a Doctrine document manager.
58
     *
59
     * @param array $options
60
     *
61
     * @throws \InvalidArgumentException
62
     * @throws \RuntimeException
63
     *
64
     * @return \Doctrine\ODM\MongoDB\DocumentManager
65
     */
66
    public static function build(array $options)
67
    {
68
        $options = array_merge(static::$defaultOptions, $options);
69
70
        static::setupAnnotationMetadata($options);
71
72
        $config = static::getConfiguration($options);
73
        static::setupMetadataDriver($config, self::getMetadataDriver($options));
74
        static::setupDefaultDatabase($config, $options);
75
        static::setupProxy($config, $options);
76
        static::setupHydrator($config, $options);
77
        static::setupLogger($config, $options);
78
79
        return DocumentManager::create(
80
            self::getConnection($config, $options),
81
            $config,
82
            $options['event_manager']
83
        );
84
    }
85
86
    /**
87
     * Create Doctrine ODM bare configuration.
88
     *
89
     * @param array $options
90
     *
91
     * @throws \InvalidArgumentException
92
     *
93
     * @return \Doctrine\ODM\MongoDB\Configuration
94
     */
95
    protected static function getConfiguration(array $options)
96
    {
97
        $cacheDriver = static::getCacheDriver(
98
            $options['cache_driver'],
99
            $options['cache_namespace'] ?: 'odm_dc2_' . sha1($options['proxy_path'] ?: sys_get_temp_dir()) . '_'
100
        );
101
102
        $config = new Configuration();
103
        $config->setMetadataCacheImpl($cacheDriver);
104
105
        return $config;
106
    }
107
108
    /**
109
     * Create metadata driver.
110
     *
111
     * @param array $options
112
     *
113
     * @throws \RuntimeException
114
     *
115
     * @return \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use AnnotationDriver|XmlDriv...lDriver|StaticPHPDriver.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
116
     */
117
    protected static function getMetadataDriver(array $options)
118
    {
119
        if ($options['annotation_paths']) {
120
            return new AnnotationDriver(new AnnotationReader, (array) $options['annotation_paths']);
121
        }
122
123
        if ($options['xml_paths']) {
124
            return new XmlDriver((array) $options['xml_paths'], '.xml');
125
        }
126
127
        if ($options['yaml_paths']) {
128
            return new YamlDriver((array) $options['yaml_paths'], '.yml');
129
        }
130
131
        if ($options['php_paths']) {
132
            return new StaticPHPDriver((array) $options['php_paths']);
133
        }
134
135
        throw new \RuntimeException('No Metadata paths defined');
136
    }
137
138
    /**
139
     * Setup default database.
140
     *
141
     * @param \Doctrine\ODM\MongoDB\Configuration $config
142
     * @param array                               $options
143
     */
144
    protected static function setupDefaultDatabase(Configuration $config, array $options)
145
    {
146
        if ($options['default_database']) {
147
            $config->setDefaultDB($options['default_database']);
148
        }
149
    }
150
151
    /**
152
     * Setup hydrators.
153
     *
154
     * @param \Doctrine\ODM\MongoDB\Configuration $config
155
     * @param array                               $options
156
     */
157
    protected static function setupHydrator(Configuration $config, array $options)
158
    {
159
        $config->setHydratorDir((string) ($options['hydrator_path'] ?: sys_get_temp_dir()));
160
161
        $config->setHydratorNamespace((string) $options['hydrators_namespace']);
162
163
        $config->setAutoGenerateHydratorClasses((bool) $options['auto_generate_hydrators']);
164
    }
165
166
    /**
167
     * Setup logger.
168
     *
169
     * @param \Doctrine\ODM\MongoDB\Configuration $config
170
     * @param array                               $options
171
     */
172
    protected static function setupLogger(Configuration $config, array $options)
173
    {
174
        if ($options['logger_callable']) {
175
            $config->setLoggerCallable($options['logger_callable']);
176
        }
177
    }
178
179
    /**
180
     * Create MongoDB Connection.
181
     *
182
     * @param \Doctrine\ODM\MongoDB\Configuration $config
183
     * @param array                               $options
184
     *
185
     * @throws \InvalidArgumentException
186
     * @throws \RuntimeException
187
     *
188
     * @return \Doctrine\MongoDB\Connection
189
     */
190
    protected static function getConnection(Configuration $config, array $options)
191
    {
192
        $connection = $options['connection'];
193
194
        switch (true) {
195
            case (is_array($connection)):
196
                $connection = new Connection(
197
                    isset($options['connection']['server']) ? $options['connection']['server'] : null,
198
                    isset($options['connection']['options']) ? $options['connection']['options'] : [],
199
                    $config,
200
                    $options['event_manager']
201
                );
202
                break;
203
204
            case ($connection instanceof Connection):
205
                if ($options['event_manager'] !== null
206
                    && $connection->getEventManager() !== $options['event_manager']
207
                ) {
208
                    throw new \RuntimeException(
209
                        'Cannot use different EventManager instances for DocumentManager and Connection.'
210
                    );
211
                }
212
                break;
213
214
            default:
215
                throw new \InvalidArgumentException('Invalid argument: ' . $connection);
216
        }
217
218
        return $connection;
219
    }
220
}
221