Configuration::getConfigTreeBuilder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
namespace As3\Bundle\ModlrBundle\DependencyInjection;
4
5
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
6
use Symfony\Component\Config\Definition\ConfigurationInterface;
7
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
8
9
/**
10
 * Validates and merges configuration for Modlr.
11
 *
12
 * @author  Jacob Bare <[email protected]>
13
 */
14
class Configuration implements ConfigurationInterface
15
{
16
    /**
17
     * {@inheritDoc}
18
     */
19
    public function getConfigTreeBuilder()
20
    {
21
        $treeBuilder = new TreeBuilder();
22
        $treeBuilder->root('as3_modlr')
23
            ->children()
24
                ->append($this->getAdapterNode())
25
                ->append($this->getMetadataNode())
26
                ->append($this->getPersistersNode())
27
                ->append($this->getRestNode())
28
                ->append($this->getSearchClientsNode())
29
            ->end()
30
        ;
31
        return $treeBuilder;
32
    }
33
34
    /**
35
     * Creates a root config node with the provided key.
36
     *
37
     * @param   string $key
38
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
39
     */
40
    private function createRootNode($key)
41
    {
42
        $treeBuilder = new TreeBuilder();
43
        return $treeBuilder->root($key);
44
    }
45
46
    /**
47
     * Formats the root REST endpoint.
48
     *
49
     * @param   string  $endpoint
50
     * @return  string
51
     */
52
    private function formatRestEndpoint($endpoint)
53
    {
54
        return sprintf('%s', trim($endpoint, '/'));
55
    }
56
57
    /**
58
     * Gets the api adapter configuration node.
59
     *
60
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
61
     */
62 View Code Duplication
    private function getAdapterNode()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
63
    {
64
        $node = $this->createRootNode('adapter');
65
        return $node
66
            ->isRequired()
67
            ->addDefaultsIfNotSet()
68
            ->children()
69
                ->enumNode('type')
70
                    ->values(['jsonapiorg', null])
71
                ->end()
72
                ->scalarNode('service')->cannotBeEmpty()->end()
73
            ->end()
74
            ->validate()
75
                ->always(function($v) {
76
                    $this->validateAdapter($v);
77
                    return $v;
78
                })
79
            ->end()
80
        ;
81
    }
82
83
    /**
84
     * Gets the metadata configuration node.
85
     *
86
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
87
     */
88
    private function getMetadataNode()
89
    {
90
        $node = $this->createRootNode('metadata');
91
        return $node
92
            ->addDefaultsIfNotSet()
93
            ->children()
94
                ->arrayNode('drivers')
95
                    ->defaultValue(['default' => ['type' => 'yml']])
96
                    ->useAttributeAsKey('name')
97
                    ->prototype('array')
98
                        ->performNoDeepMerging()
99
                        ->children()
100
101
                            ->enumNode('type')->defaultValue('yml')
102
                                ->values(['yml', null])
103
                            ->end()
104
                            ->scalarNode('service')->cannotBeEmpty()->end()
105
106
                            ->arrayNode('parameters')
107
                                ->performNoDeepMerging()
108
                                ->prototype('variable')->end()
109
                            ->end()
110
111
                        ->end()
112
                    ->end()
113
                    ->validate()
114
                        ->always(function($v) {
115
                            $this->validateMetadataDrivers($v);
116
                            return $v;
117
                        })
118
                    ->end()
119
                ->end()
120
121
                ->arrayNode('cache')
122
                    ->canBeDisabled()
123
                    ->children()
124
125
                        ->enumNode('type')->defaultValue('file')
126
                            ->values(['file', 'binary_file', 'redis', null])
127
                        ->end()
128
                        ->scalarNode('service')->cannotBeEmpty()->end()
129
130
                        ->arrayNode('parameters')
131
                            ->performNoDeepMerging()
132
                            ->prototype('variable')->end()
133
                        ->end()
134
135
                    ->end()
136
137
                    ->validate()
138
                        ->always(function($v) {
139
                            $this->validateMetadataCache($v);
140
                            return $v;
141
                        })
142
                    ->end()
143
                ->end()
144
            ->end()
145
        ;
146
    }
147
148
    /**
149
     * Gets the persisters configuration node.
150
     *
151
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
152
     */
153 View Code Duplication
    private function getPersistersNode()
154
    {
155
        $node = $this->createRootNode('persisters');
156
        return $node
157
            ->isRequired()
158
            ->useAttributeAsKey('name')
159
            ->prototype('array')
160
                ->children()
161
162
                    ->enumNode('type')
163
                        ->values(['mongodb', null])
164
                    ->end()
165
                    ->scalarNode('service')->cannotBeEmpty()->end()
166
167
                    ->arrayNode('parameters')
168
                        ->performNoDeepMerging()
169
                        ->prototype('variable')->end()
170
                    ->end()
171
                ->end()
172
            ->end()
173
            ->validate()
174
                ->always(function($v) {
175
                    $this->validatePersisters($v);
176
                    return $v;
177
                })
178
            ->end()
179
        ;
180
    }
181
182
    /**
183
     * Gets the rest configuration node.
184
     *
185
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
186
     */
187 View Code Duplication
    private function getRestNode()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    {
189
        $node = $this->createRootNode('rest');
190
        return $node
191
            ->addDefaultsIfNotSet()
192
            ->children()
193
                ->scalarNode('root_endpoint')->isRequired()->cannotBeEmpty()->defaultValue('modlr/api')
194
                    ->validate()
195
                        ->always(function($v) {
196
                            $v = $this->formatRestEndpoint($v);
197
                            return $v;
198
                        })
199
                    ->end()
200
                ->end()
201
                ->booleanNode('debug')->defaultValue(false)->end()
202
            ->end()
203
204
        ;
205
    }
206
207
    /**
208
     * Gets the search clients configuration node.
209
     *
210
     * @return  \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
211
     */
212 View Code Duplication
    private function getSearchClientsNode()
213
    {
214
        $node = $this->createRootNode('search_clients');
215
        return $node
216
            ->isRequired()
217
            ->useAttributeAsKey('name')
218
            ->prototype('array')
219
                ->children()
220
221
                    ->enumNode('type')
222
                        ->values(['elastic', null])
223
                    ->end()
224
                    ->scalarNode('service')->cannotBeEmpty()->end()
225
226
                    ->arrayNode('parameters')
227
                        ->performNoDeepMerging()
228
                        ->prototype('variable')->end()
229
                    ->end()
230
                ->end()
231
            ->end()
232
            ->validate()
233
                ->always(function($v) {
234
                    $this->validateSearchClients($v);
235
                    return $v;
236
                })
237
            ->end()
238
        ;
239
    }
240
241
    /**
242
     * Validates the api adapter config.
243
     *
244
     * @param   array   $adapter
245
     * @return  self
246
     * @throws  InvalidConfigurationException
247
     */
248
    private function validateAdapter(array $adapter)
249
    {
250
        $this->validateTypeAndService($adapter, 'as3_modlr.adapter');
251
        switch ($adapter['type']) {
252
            case 'jsonapiorg':
253
                $this->validateLibClassExists('Api\JsonApiOrg\Adapter', 'as3_modlr.adapter.type');
254
                break;
255
            default:
256
                break;
257
        }
258
        return $this;
259
    }
260
261
    /**
262
     * Validates that a library class name exists.
263
     *
264
     * @param   string  $subClass
265
     * @param   string  $path
266
     * @throws  InvalidConfigurationException
267
     */
268
    private function validateLibClassExists($subClass, $path)
269
    {
270
        $class = Utility::getLibraryClass($subClass);
271
        if (false === class_exists($class)) {
272
            throw new InvalidConfigurationException(sprintf('The library class "%s" was not found for "%s" - was the library installed?', $class, $path));
273
        }
274
    }
275
276
    /**
277
     * Validates the metadata cache config.
278
     *
279
     * @param   array   $config
280
     * @return  self
281
     * @throws  InvalidConfigurationException
282
     */
283
    private function validateMetadataCache(array $config)
284
    {
285
        if (false === $config['enabled']) {
286
            return $this;
287
        }
288
289
        $this->validateTypeAndService($config, 'as3_modlr.metadata.cache');
290
        switch ($config['type']) {
291
            case 'redis':
292
                $this->validateMetadataCacheRedis($config);
293
                break;
294
            default:
295
                break;
296
        }
297
        return $this;
298
    }
299
300
    /**
301
     * Validates the Redis metadata cache config.
302
     *
303
     * @param   array   $config
304
     * @throws  InvalidConfigurationException
305
     */
306
    private function validateMetadataCacheRedis(array $config)
307
    {
308
        if (!isset($config['parameters']['handler'])) {
309
            throw new InvalidConfigurationException('A Redis handler service name must be defined for "as3_modlr.metadata.cache.parameters.handler"');
310
        }
311
    }
312
313
    /**
314
     * Validates the metadata drivers config.
315
     *
316
     * @param   array   $drivers
317
     * @return  self
318
     * @throws  InvalidConfigurationException
319
     */
320
    private function validateMetadataDrivers(array $drivers)
321
    {
322
        foreach ($drivers as $name => $config) {
323
            $this->validateTypeAndService($config, sprintf('as3_modlr.metadata.drivers.%s', $name));
324
        }
325
        return $this;
326
    }
327
328
    /**
329
     * Validates the MongoDb persister config.
330
     *
331
     * @param   array   $config
332
     * @throws  InvalidConfigurationException
333
     */
334
    private function validatePersisterMongoDb(array $config)
335
    {
336
        if (!isset($config['parameters']['host'])) {
337
            throw new InvalidConfigurationException(sprintf('The MongoDB persister requires a value for "as3_modlr.persisters.%s.parameters.host"', $name));
338
        }
339
    }
340
341
    /**
342
     * Validates the persisters config.
343
     *
344
     * @param   array   $persisters
345
     * @return  self
346
     * @throws  InvalidConfigurationException
347
     */
348
    private function validatePersisters(array $persisters)
349
    {
350
        foreach ($persisters as $name => $config) {
351
            $this->validateTypeAndService($config, sprintf('as3_modlr.persisters.%s', $name));
352
            switch ($config['type']) {
353
                case 'mongodb':
354
                    $this->validateLibClassExists('Persister\MongoDb\Persister', sprintf('as3_modlr.persisters.%s.type', $name));
355
                    $this->validatePersisterMongoDb($config);
356
                    break;
357
                default:
358
                    break;
359
            }
360
        }
361
    }
362
363
    /**
364
     * Validates the search clients config.
365
     *
366
     * @param   array   $clients
367
     * @return  self
368
     * @throws  InvalidConfigurationException
369
     */
370
    private function validateSearchClients(array $clients)
371
    {
372
        foreach ($clients as $name => $config) {
373
            $this->validateTypeAndService($config, sprintf('as3_modlr.search_clients.%s', $name));
374
            switch ($config['type']) {
375
                case 'elastic':
376
                    $this->validateLibClassExists('Search\Elastic\Client', sprintf('as3_modlr.search_clients.%s.type', $name));
377
                    break;
378
                default:
379
                    break;
380
            }
381
        }
382
    }
383
384
    /**
385
     * Validates a configuration that uses type and service as options.
386
     *
387
     * @param   array   $config
388
     * @param   string  $path
389
     * @throws  InvalidArgumentException
390
     */
391
    private function validateTypeAndService(array $config, $path)
392
    {
393 View Code Duplication
        if (!isset($config['type']) && !isset($config['service'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
394
            throw new InvalidConfigurationException(sprintf('You must set one of "type" or "service" for "%s"', $path));
395
        }
396 View Code Duplication
        if (isset($config['type']) && isset($config['service'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
397
            throw new InvalidConfigurationException(sprintf('You cannot set both "type" and "service" for "%s" - please choose one.', $path));
398
        }
399
    }
400
}
401