Completed
Push — master ( f29a75...c4e6f7 )
by Julián
02:15
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\MappingDriverChain;
14
use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver;
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\Mapping\Driver\AnnotationDriver;
20
use Doctrine\ODM\MongoDB\Mapping\Driver\XmlDriver;
21
use Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver;
22
23
/**
24
 * Doctrine Document Manager service builder.
25
 */
26
class DocumentManagerBuilder
27
{
28
    use ObjectManagerTrait;
29
30
    /**
31
     * Default configuration options.
32
     *
33
     * @var array
34
     */
35
    protected static $defaultOptions = [
36
        'connection' => null,
37
        'cache_driver' => null,
38
        'cache_namespace' => null,
39
        'annotation_files' => [],
40
        'annotation_namespaces' => [],
41
        'annotation_autoloaders' => [],
42
        'annotation_paths' => null,
43
        'xml_paths' => null,
44
        'yaml_paths' => null,
45
        'php_paths' => null,
46
        'default_database' => null,
47
        'proxy_path' => null,
48
        'proxies_namespace' => 'DoctrineODMProxy',
49
        'auto_generate_proxies' => AbstractProxyFactory::AUTOGENERATE_NEVER,
50
        'hydrator_path' => null,
51
        'hydrators_namespace' => 'DoctrineODMHydrator',
52
        'auto_generate_hydrators' => AbstractProxyFactory::AUTOGENERATE_NEVER,
53
        'logger_callable' => null,
54
        'event_manager' => null,
55
    ];
56
57
    /**
58
     * Create a Doctrine document manager.
59
     *
60
     * @param array $options
61
     *
62
     * @throws \InvalidArgumentException
63
     * @throws \RuntimeException
64
     *
65
     * @return \Doctrine\ODM\MongoDB\DocumentManager
66
     */
67
    public static function build(array $options)
68
    {
69
        $options = array_merge(static::$defaultOptions, $options);
70
71
        AnnotationDriver::registerAnnotationClasses();
72
        static::setupAnnotationMetadata($options);
73
74
        $config = static::getConfiguration($options);
75
        static::setupMetadataDriver($config, $options);
76
        static::setupDefaultDatabase($config, $options);
77
        static::setupProxy($config, $options);
78
        static::setupHydrator($config, $options);
79
        static::setupLogger($config, $options);
80
81
        return DocumentManager::create(
82
            self::getConnection($config, $options),
83
            $config,
84
            $options['event_manager']
85
        );
86
    }
87
88
    /**
89
     * Create Doctrine ODM bare configuration.
90
     *
91
     * @param array $options
92
     *
93
     * @throws \InvalidArgumentException
94
     *
95
     * @return \Doctrine\ODM\MongoDB\Configuration
96
     */
97
    protected static function getConfiguration(array $options)
98
    {
99
        $cacheDriver = static::getCacheDriver(
100
            $options['cache_driver'],
101
            $options['cache_namespace'] ?: 'odm_dc2_' . sha1($options['proxy_path'] ?: sys_get_temp_dir()) . '_'
102
        );
103
104
        $config = new Configuration();
105
        $config->setMetadataCacheImpl($cacheDriver);
106
107
        return $config;
108
    }
109
110
    /**
111
     * Create Doctrine ODM configuration.
112
     *
113
     * @param \Doctrine\ODM\MongoDB\Configuration $config
114
     * @param array                               $options
115
     *
116
     * @throws \RuntimeException
117
     */
118
    protected static function setupMetadataDriver(Configuration $config, array $options)
119
    {
120
        $metadataDriver = new MappingDriverChain;
121
        $metadataDriver->setDefaultDriver(self::getMetadataDriver($options));
122
123
        $config->setMetadataDriverImpl($metadataDriver);
124
    }
125
126
    /**
127
     * @param array $options
128
     *
129
     * @throws \RuntimeException
130
     *
131
     * @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...
132
     */
133
    protected static function getMetadataDriver(array $options)
134
    {
135
        if ($options['annotation_paths']) {
136
            return new AnnotationDriver(new AnnotationReader, (array) $options['annotation_paths']);
137
        }
138
139
        if ($options['xml_paths']) {
140
            return new XmlDriver((array) $options['xml_paths'], '.xml');
141
        }
142
143
        if ($options['yaml_paths']) {
144
            return new YamlDriver((array) $options['yaml_paths'], '.yml');
145
        }
146
147
        if ($options['php_paths']) {
148
            return new StaticPHPDriver((array) $options['php_paths']);
149
        }
150
151
        throw new \RuntimeException('No Metadata paths defined');
152
    }
153
154
    /**
155
     * Setup default database.
156
     *
157
     * @param \Doctrine\ODM\MongoDB\Configuration $config
158
     * @param array                               $options
159
     */
160
    protected static function setupDefaultDatabase(Configuration $config, array $options)
161
    {
162
        if ($options['default_database']) {
163
            $config->setDefaultDB($options['default_database']);
164
        }
165
    }
166
167
    /**
168
     * Setup hydrators.
169
     *
170
     * @param \Doctrine\ODM\MongoDB\Configuration $config
171
     * @param array                               $options
172
     */
173
    protected static function setupHydrator(Configuration $config, array $options)
174
    {
175
        $config->setHydratorDir((string) ($options['hydrator_path'] ?: sys_get_temp_dir()));
176
177
        $config->setHydratorNamespace((string) $options['hydrators_namespace']);
178
179
        $config->setAutoGenerateHydratorClasses((bool) $options['auto_generate_hydrators']);
180
    }
181
182
    /**
183
     * Setup logger.
184
     *
185
     * @param \Doctrine\ODM\MongoDB\Configuration $config
186
     * @param array                               $options
187
     */
188
    protected static function setupLogger(Configuration $config, array $options)
189
    {
190
        if ($options['logger_callable']) {
191
            $config->setLoggerCallable($options['logger_callable']);
192
        }
193
    }
194
195
    /**
196
     * Create MongoDB Connection.
197
     *
198
     * @param \Doctrine\ODM\MongoDB\Configuration $config
199
     * @param array                               $options
200
     *
201
     * @throws \InvalidArgumentException
202
     * @throws \RuntimeException
203
     *
204
     * @return \Doctrine\MongoDB\Connection
205
     */
206
    protected static function getConnection(Configuration $config, array $options)
207
    {
208
        $connection = $options['connection'];
209
210
        switch (true) {
211
            case (is_array($connection)):
212
                $connection = new Connection(
213
                    isset($options['connection']['server']) ? $options['connection']['server'] : null,
214
                    isset($options['connection']['options']) ? $options['connection']['options'] : [],
215
                    $config,
216
                    $options['event_manager']
217
                );
218
                break;
219
220
            case ($connection instanceof Connection):
221
                if ($options['event_manager'] !== null
222
                    && $connection->getEventManager() !== $options['event_manager']
223
                ) {
224
                    throw new \RuntimeException(
225
                        'Cannot use different EventManager instances for DocumentManager and Connection.'
226
                    );
227
                }
228
                break;
229
230
            default:
231
                throw new \InvalidArgumentException('Invalid argument: ' . $connection);
232
        }
233
234
        return $connection;
235
    }
236
}
237