Completed
Push — master ( a0c9a9...39a50b )
by Julián
02:54
created

EntityManagerBuilder::setupQuoteStrategy()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 3
eloc 5
nc 4
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\AnnotationRegistry;
13
use Doctrine\Common\Cache\Cache;
14
use Doctrine\Common\Proxy\AbstractProxyFactory;
15
use Doctrine\DBAL\Connection;
16
use Doctrine\DBAL\Types\Type;
17
use Doctrine\ORM\Configuration;
18
use Doctrine\ORM\EntityManager;
19
use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
20
use Doctrine\ORM\Mapping\Driver\StaticPHPDriver;
21
use Doctrine\ORM\Mapping\NamingStrategy;
22
use Doctrine\ORM\Mapping\QuoteStrategy;
23
use Doctrine\ORM\Mapping\UnderscoreNamingStrategy;
24
use Doctrine\ORM\Tools\Setup;
25
26
/**
27
 * Doctrine Entity Manager service builder
28
 */
29
class EntityManagerBuilder
30
{
31
    /**
32
     * Default configuration options.
33
     *
34
     * @var array
35
     */
36
    protected static $defaultOptions = [
37
        'connection' => null,
38
        'cache_driver' => 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
        'naming_strategy' => null,
47
        'quote_strategy' => null,
48
        'proxy_path' => null,
49
        'proxies_namespace' => null,
50
        'auto_generate_proxies' => AbstractProxyFactory::AUTOGENERATE_NEVER,
51
        'sql_logger' => null,
52
        'event_manager' => null,
53
        'custom_types' => [],
54
        'string_functions' => [],
55
        'numeric_functions' => [],
56
        'datetime_functions' => [],
57
    ];
58
59
    /**
60
     * Create a Doctrine entity manager.
61
     *
62
     * @param array $options
63
     *
64
     * @throws \InvalidArgumentException
65
     *
66
     * @return \Doctrine\ORM\EntityManager
67
     */
68
    public static function build(array $options)
69
    {
70
        $options = array_merge(static::$defaultOptions, $options);
71
72
        if ($options['cache_driver'] !== null && !$options['cache_driver'] instanceof Cache) {
73
            throw new \InvalidArgumentException('Cache Driver provided is not valid');
74
        }
75
76
        static::setupAnnotationMetadata($options);
77
78
        $config = static::createConfiguration($options);
79
        if (!$config instanceof Configuration) {
80
            throw new \InvalidArgumentException('No Metadata Driver defined');
81
        }
82
83
        static::setupNamingStrategy($config, $options);
84
85
        static::setupQuoteStrategy($config, $options);
86
87
        static::setupProxy($config, $options);
88
89
        static::setupSQLLogger($config, $options);
90
91
        static::setupCustomDQLFunctions($config, $options);
92
93
        $entityManager = EntityManager::create($options['connection'], $config, $options['event_manager']);
94
95
        static::setupCustomDBALTypes($entityManager->getConnection(), $options);
0 ignored issues
show
Bug introduced by
$entityManager->getConnection() cannot be passed to setupcustomdbaltypes() as the parameter $connection expects a reference.
Loading history...
96
97
        return $entityManager;
98
    }
99
100
    /**
101
     * Set up annotation metadata.
102
     *
103
     * @param array $options
104
     */
105
    protected static function setupAnnotationMetadata(array $options)
106
    {
107
        foreach ($options['annotation_files'] as $file) {
108
            AnnotationRegistry::registerFile($file);
109
        }
110
111
        AnnotationRegistry::registerAutoloadNamespaces($options['annotation_namespaces']);
112
113
        foreach ($options['annotation_autoloaders'] as $autoloader) {
114
            AnnotationRegistry::registerLoader($autoloader);
115
        }
116
    }
117
118
    /**
119
     * Create Doctrine configuration.
120
     *
121
     * @param array $options
122
     *
123
     * @return \Doctrine\ORM\Configuration|null
124
     */
125
    protected static function createConfiguration(array $options)
126
    {
127
        if ($options['annotation_paths']) {
128
            return Setup::createAnnotationMetadataConfiguration(
129
                static::normalizePaths($options['annotation_paths']),
130
                false,
131
                $options['proxy_path'],
132
                $options['cache_driver'],
133
                false
134
            );
135
        }
136
137
        if ($options['xml_paths']) {
138
            return Setup::createXMLMetadataConfiguration(
139
                static::normalizePaths($options['xml_paths']),
140
                false,
141
                $options['proxy_path'],
142
                $options['cache_driver']
143
            );
144
        }
145
146
        if ($options['yaml_paths']) {
147
            return Setup::createYAMLMetadataConfiguration(
148
                static::normalizePaths($options['yaml_paths']),
149
                false,
150
                $options['proxy_path'],
151
                $options['cache_driver']
152
            );
153
        }
154
155
        if ($options['php_paths']) {
156
            $config = Setup::createConfiguration(
157
                false,
158
                $options['proxy_path'],
159
                $options['cache_driver']
160
            );
161
            $config->setMetadataDriverImpl(new StaticPHPDriver(static::normalizePaths($options['php_paths'])));
0 ignored issues
show
Deprecated Code introduced by
The class Doctrine\ORM\Mapping\Driver\StaticPHPDriver has been deprecated with message: this driver will be removed. Use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver instead

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
162
163
            return $config;
164
        }
165
166
        return null;
167
    }
168
169
    /**
170
     * Normalize paths to array.
171
     *
172
     * @param array|string $paths
173
     *
174
     * @return array
175
     */
176
    protected static function normalizePaths($paths)
177
    {
178
        return is_array($paths) ? $paths : [$paths];
179
    }
180
181
    /**
182
     * Setup naming strategy.
183
     *
184
     * @param \Doctrine\ORM\Configuration $config
185
     * @param array                       $options
186
     *
187
     * @throws \InvalidArgumentException
188
     */
189
    protected static function setupNamingStrategy(Configuration &$config, array $options)
190
    {
191
        $namingStrategy = $options['naming_strategy'] ?: new UnderscoreNamingStrategy(CASE_LOWER);
192
        if (!$namingStrategy instanceof NamingStrategy) {
193
            throw new \InvalidArgumentException('Naming strategy provided is not valid');
194
        }
195
196
        $config->setNamingStrategy($namingStrategy);
197
    }
198
199
    /**
200
     * Setup quote strategy.
201
     *
202
     * @param \Doctrine\ORM\Configuration $config
203
     * @param array                       $options
204
     *
205
     * @throws \InvalidArgumentException
206
     */
207
    protected static function setupQuoteStrategy(Configuration &$config, array $options)
208
    {
209
        $quoteStrategy = $options['quote_strategy'] ?: new DefaultQuoteStrategy();
210
        if (!$quoteStrategy instanceof QuoteStrategy) {
211
            throw new \InvalidArgumentException('Quote strategy provided is not valid');
212
        }
213
214
        $config->setQuoteStrategy($quoteStrategy);
215
    }
216
217
    /**
218
     * Setup proxies.
219
     *
220
     * @param \Doctrine\ORM\Configuration $config
221
     * @param array                       $options
222
     */
223
    protected static function setupProxy(Configuration &$config, array $options)
224
    {
225
        $proxiesNamespace = $options['proxies_namespace'] ? $options['proxies_namespace'] : 'DoctrineORMProxy';
226
        $config->setProxyNamespace((string) $proxiesNamespace);
227
228
        $config->setAutoGenerateProxyClasses(intval($options['auto_generate_proxies']));
229
    }
230
231
    /**
232
     * Setup SQL logger.
233
     *
234
     * @param \Doctrine\ORM\Configuration $config
235
     * @param array                       $options
236
     */
237
    protected static function setupSQLLogger(Configuration &$config, array $options)
238
    {
239
        if ($options['sql_logger']) {
240
            $config->setSQLLogger($options['sql_logger']);
241
        }
242
    }
243
244
    /**
245
     * Setup custom DQL functions.
246
     *
247
     * @param \Doctrine\ORM\Configuration $config
248
     * @param array                       $options
249
     */
250
    protected static function setupCustomDQLFunctions(Configuration &$config, array $options)
251
    {
252
        $config->setCustomStringFunctions($options['string_functions']);
253
254
        $config->setCustomNumericFunctions($options['numeric_functions']);
255
256
        $config->setCustomDatetimeFunctions($options['datetime_functions']);
257
    }
258
259
    /**
260
     * Setup Custom DBAL types.
261
     *
262
     * @param \Doctrine\DBAL\Connection $connection
263
     * @param array                     $options
264
     */
265
    protected static function setupCustomDBALTypes(Connection &$connection, array $options)
266
    {
267
        foreach ($options['custom_types'] as $name => $class) {
268
            Type::addType($name, $class);
269
            $connection->getDatabasePlatform()->registerDoctrineTypeMapping($name, $name);
270
        }
271
    }
272
}
273