Completed
Pull Request — master (#112)
by David
10:10
created

Configuration::addSharedPluginNodes()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 113
Code Lines 94

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 52
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 113
ccs 52
cts 52
cp 1
rs 8.1463
cc 6
eloc 94
nc 32
nop 2
crap 6

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Http\HttplugBundle\DependencyInjection;
4
5
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
6
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
7
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
8
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
9
use Symfony\Component\Config\Definition\ConfigurationInterface;
10
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
11
12
/**
13
 * This class contains the configuration information for the bundle.
14
 *
15
 * This information is solely responsible for how the different configuration
16
 * sections are normalized, and merged.
17
 *
18
 * @author David Buchmann <[email protected]>
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class Configuration implements ConfigurationInterface
22
{
23
    /**
24
     * Whether to use the debug mode.
25
     *
26
     * @see https://github.com/doctrine/DoctrineBundle/blob/v1.5.2/DependencyInjection/Configuration.php#L31-L41
27
     *
28
     * @var bool
29
     */
30
    private $debug;
31
32
    /**
33
     * @param bool $debug
34 12
     */
35
    public function __construct($debug)
36 12
    {
37 12
        $this->debug = (bool) $debug;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42 12
     */
43
    public function getConfigTreeBuilder()
44 12
    {
45 12
        $treeBuilder = new TreeBuilder();
46
        $rootNode = $treeBuilder->root('httplug');
47 12
48 12
        $this->configureClients($rootNode);
49
        $this->configureSharedPlugins($rootNode);
50
51 12
        $rootNode
52
            ->validate()
53 11
                ->ifTrue(function ($v) {
54 11
                    return !empty($v['classes']['client'])
55 8
                        || !empty($v['classes']['message_factory'])
56 11
                        || !empty($v['classes']['uri_factory'])
57 12
                        || !empty($v['classes']['stream_factory']);
58
                })
59 3
                ->then(function ($v) {
60 3
                    foreach ($v['classes'] as $key => $class) {
61 1
                        if (null !== $class && !class_exists($class)) {
62 1
                            throw new InvalidConfigurationException(sprintf(
63 1
                                'Class %s specified for httplug.classes.%s does not exist.',
64
                                $class,
65 1
                                $key
66
                            ));
67 2
                        }
68
                    }
69 2
70 12
                    return $v;
71 12
                })
72 12
            ->end()
73 12
            ->beforeNormalization()
74 12
                ->ifTrue(function ($v) {
75 12
                    return is_array($v) && array_key_exists('toolbar', $v) && is_array($v['toolbar']);
76 12
                })
77 12
                ->then(function ($v) {
78 12
                    if (array_key_exists('profiling', $v)) {
79 12
                        throw new InvalidConfigurationException('Can\'t configure both "toolbar" and "profiling" section. The "toolbar" config is deprecated as of version 1.3.0, please only use "profiling".');
80 12
                    }
81 12
82 12
                    @trigger_error('"httplug.toolbar" config is deprecated since version 1.3 and will be removed in 2.0. Use "httplug.profiling" instead.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
83 12
84 12
                    if (array_key_exists('enabled', $v['toolbar']) && 'auto' === $v['toolbar']['enabled']) {
85 12
                        @trigger_error('"auto" value in "httplug.toolbar" config is deprecated since version 1.3 and will be removed in 2.0. Use a boolean value instead.', E_USER_DEPRECATED);
1 ignored issue
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
86 12
                        $v['toolbar']['enabled'] = $this->debug;
87 12
                    }
88 12
89 12
                    $v['profiling'] = $v['toolbar'];
90 12
91 12
                    unset($v['toolbar']);
92 12
93 12
                    return $v;
94 12
                })
95 12
            ->end()
96 12
            ->fixXmlConfig('client')
97 12
            ->children()
98 12
                ->arrayNode('main_alias')
99 12
                    ->addDefaultsIfNotSet()
100
                    ->info('Configure which service the main alias point to.')
101 1
                    ->children()
102 12
                        ->scalarNode('client')->defaultValue('httplug.client.default')->end()
103 12
                        ->scalarNode('message_factory')->defaultValue('httplug.message_factory.default')->end()
104 12
                        ->scalarNode('uri_factory')->defaultValue('httplug.uri_factory.default')->end()
105 12
                        ->scalarNode('stream_factory')->defaultValue('httplug.stream_factory.default')->end()
106 12
                    ->end()
107 12
                ->end()
108 12
                ->arrayNode('classes')
109 12
                    ->addDefaultsIfNotSet()
110 12
                    ->info('Overwrite a service class instead of using the discovery mechanism.')
111 12
                    ->children()
112 12
                        ->scalarNode('client')->defaultNull()->end()
113 12
                        ->scalarNode('message_factory')->defaultNull()->end()
114 12
                        ->scalarNode('uri_factory')->defaultNull()->end()
115 12
                        ->scalarNode('stream_factory')->defaultNull()->end()
116 12
                    ->end()
117 12
                ->end()
118 12
                ->arrayNode('profiling')
119 12
                    ->addDefaultsIfNotSet()
120 12
                    ->treatFalseLike(['enabled' => false])
121 12
                    ->treatTrueLike(['enabled' => true])
122 12
                    ->treatNullLike(['enabled' => $this->debug])
123 12
                    ->info('Extend the debug profiler with information about requests.')
124 12
                    ->children()
125 12
                        ->booleanNode('enabled')
126 12
                            ->info('Turn the toolbar on or off. Defaults to kernel debug mode.')
127 12
                            ->defaultValue($this->debug)
128 12
                        ->end()
129
                        ->scalarNode('formatter')->defaultNull()->end()
130 12
                        ->integerNode('captured_body_length')
131
                            ->defaultValue(0)
132
                            ->info('Limit long HTTP message bodies to x characters. If set to 0 we do not read the message body. Only available with the default formatter (FullHttpMessageFormatter).')
133 12
                        ->end()
134
                    ->end()
135 12
                ->end()
136 12
                ->arrayNode('discovery')
137 12
                    ->addDefaultsIfNotSet()
138
                    ->info('Control what clients should be found by the discovery.')
139 3
                    ->children()
140
                        ->scalarNode('client')
141 3
                            ->defaultValue('auto')
142
                            ->info('Set to "auto" to see auto discovered client in the web profiler. If provided a service id for a client then this client will be found by auto discovery.')
143
                        ->end()
144
                        ->scalarNode('async_client')
145 12
                            ->defaultNull()
146 12
                            ->info('Set to "auto" to see auto discovered client in the web profiler. If provided a service id for a client then this client will be found by auto discovery.')
147 12
                        ->end()
148 12
                    ->end()
149 12
                ->end()
150 12
            ->end();
151 12
152 12
        return $treeBuilder;
153 12
    }
154 12
155 12
    private function configureClients(ArrayNodeDefinition $root)
156 12
    {
157 12
        $pluginNode = $root->children()
158 12
            ->arrayNode('clients')
159 12
                ->fixXmlConfig('plugin')
160 12
                ->validate()
161 12
                    ->ifTrue(function ($clients) {
162 12
                        foreach ($clients as $name => $config) {
163 12
                            // Make sure we only allow one of these to be true
164 12
                            return (bool) $config['flexible_client'] + (bool) $config['http_methods_client'] + (bool) $config['batch_client'] >= 2;
165 12
                        }
166 12
167 12
                        return false;
168 12
                    })
169 12
                    ->thenInvalid('A http client can\'t be decorated with both FlexibleHttpClient and HttpMethodsClient. Only one of the following options can be true. ("flexible_client", "http_methods_client")')->end()
170 12
                ->useAttributeAsKey('name')
171 12
                ->prototype('array')
172 12
                ->children()
173 12
                    ->scalarNode('factory')
174 12
                        ->isRequired()
175
                        ->cannotBeEmpty()
176
                        ->info('The service id of a factory to use when creating the adapter.')
177
                    ->end()
178
                    ->booleanNode('flexible_client')
179 12
                        ->defaultFalse()
180
                        ->info('Set to true to get the client wrapped in a FlexibleHttpClient which emulates async or sync behavior.')
181 12
                    ->end()
182 12
                    ->booleanNode('http_methods_client')
183 12
                        ->defaultFalse()
184 12
                        ->info('Set to true to get the client wrapped in a HttpMethodsClient which emulates provides functions for HTTP verbs.')
185 12
                    ->end()
186
                    ->booleanNode('batch_client')
187 12
                        ->defaultFalse()
188 12
                        ->info('Set to true to get the client wrapped in a BatchClient which allows you to send multiple request at the same time.')
189 12
                    ->end()
190 12
                    ->variableNode('config')->defaultValue([])->end()
191 12
                    ->arrayNode('plugins')
192 12
                        ->info('A list of plugin service ids and client specific plugin definitions. The order is important.')
193 12
                        ->prototype('array')
194 12
        ;
195 12
196 12
        $this->configureClientPlugins($pluginNode);
197 12
    }
198 12
199 12
    /**
200 12
     * @param ArrayNodeDefinition $root
201 12
     */
202 12
    private function configureSharedPlugins(ArrayNodeDefinition $root)
203 12
    {
204 12
        $pluginsNode = $root
205 12
            ->children()
206 12
                ->arrayNode('plugins')
207 12
                ->addDefaultsIfNotSet()
208 12
        ;
209 12
        $this->addSharedPluginNodes($pluginsNode);
210
    }
211 12
212 12
    /**
213 12
     * Configure plugins node of a client.
214 12
     *
215 12
     * @param ArrayNodeDefinition $pluginNode The node to add plugin definitions to.
216 12
     */
217 12
    private function configureClientPlugins(ArrayNodeDefinition $pluginNode)
218 12
    {
219 12
        $pluginNode
220 12
            // support having just a service id in the list
221
            ->beforeNormalization()
222 12
                ->always(function ($plugin) {
223 12
                    if (is_string($plugin)) {
224 12
                        return [
225 12
                            'reference' => [
226 12
                                'enabled' => true,
227 12
                                'id' => $plugin,
228 12
                            ],
229
                        ];
230 12
                    }
231 12
232 12
                    return $plugin;
233 12
                })
234 12
            ->end()
235 12
236 12
            ->validate()
237 12
                ->always(function ($plugins) {
238 12
                    if (isset($plugins['authentication']) && !count($plugins['authentication'])) {
239 12
                        unset($plugins['authentication']);
240
                    }
241 12
                    foreach ($plugins as $name => $definition) {
242 12
                        if (!$definition['enabled']) {
243 12
                            unset($plugins[$name]);
244 12
                        }
245 12
                    }
246 12
247 12
                    return $plugins;
248 12
                })
249 12
            ->end()
250 12
        ;
251 12
        $this->addSharedPluginNodes($pluginNode, true);
252 12
253 12
        $pluginNode
254 12
            ->children()
255 12
                ->arrayNode('reference')
256
                    ->canBeEnabled()
257 12
                    ->info('Reference to a plugin service')
258 12
                    ->children()
259 12
                        ->scalarNode('id')
260 12
                            ->info('Service id of a plugin')
261 12
                            ->isRequired()
262 12
                            ->cannotBeEmpty()
263 12
                        ->end()
264 12
                    ->end()
265
                ->end()
266 12
                ->arrayNode('add_host')
267 12
                    ->canBeEnabled()
268 12
                    ->addDefaultsIfNotSet()
269 12
                    ->info('Configure the AddHostPlugin for this client.')
270 12
                    ->children()
271 12
                        ->scalarNode('host')
272 12
                            ->info('Host name including protocol and optionally the port number, e.g. https://api.local:8000')
273
                            ->isRequired()
274 12
                            ->cannotBeEmpty()
275 12
                        ->end()
276 12
                        ->scalarNode('replace')
277 12
                            ->info('Whether to replace the host if request already specifies it')
278 12
                            ->defaultValue(false)
279 12
                        ->end()
280 12
                    ->end()
281 12
                ->end()
282 12
283 12
                // TODO add aditional plugins that are only usable on a specific client
284 12
            ->end()
285
        ->end();
286 12
    }
287 12
288 12
    /**
289 12
     * Add the definitions for shared plugin configurations.
290
     *
291
     * @param ArrayNodeDefinition $pluginNode The node to add to.
292
     * @param bool                $disableAll Some shared plugins are enabled by default. On the client, all are disabled by default.
293
     */
294
    private function addSharedPluginNodes(ArrayNodeDefinition $pluginNode, $disableAll = false)
295
    {
296 12
        $children = $pluginNode->children();
297
298 12
        $children->append($this->createAuthenticationPluginNode());
299 12
300
        $children->arrayNode('cache')
301 12
            ->canBeEnabled()
302 12
            ->addDefaultsIfNotSet()
303 12
                ->children()
304 12
                    ->scalarNode('cache_pool')
305 12
                        ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
306 2
                        ->isRequired()
307 2
                        ->cannotBeEmpty()
308 1
                    ->end()
309 1
                    ->scalarNode('stream_factory')
310 2
                        ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
311 1
                        ->defaultValue('httplug.stream_factory')
312 1
                        ->cannotBeEmpty()
313 2
                    ->end()
314 2
                    ->arrayNode('config')
315 1
                        ->addDefaultsIfNotSet()
316 1
                        ->children()
317 1
                            ->scalarNode('default_ttl')->defaultNull()->end()
318 1
                            ->scalarNode('respect_cache_headers')->defaultTrue()->end()
319 1
                        ->end()
320
                    ->end()
321 1
                ->end()
322 12
            ->end();
323 12
        // End cache plugin
324 12
325 12
        $children->arrayNode('cookie')
326 12
            ->canBeEnabled()
327 12
                ->children()
328 12
                    ->scalarNode('cookie_jar')
329 12
                        ->info('This must be a service id to a service implementing Http\Message\CookieJar')
330 12
                        ->isRequired()
331 12
                        ->cannotBeEmpty()
332 12
                    ->end()
333 12
                ->end()
334 12
            ->end();
335 12
        // End cookie plugin
336 12
337
        $decoder = $children->arrayNode('decoder');
338 12
        $disableAll ? $decoder->canBeEnabled() : $decoder->canBeDisabled();
339
        $decoder->addDefaultsIfNotSet()
340
            ->children()
341
                ->scalarNode('use_content_encoding')->defaultTrue()->end()
342
            ->end()
343
        ->end();
344
        // End decoder plugin
345
346
        $children->arrayNode('history')
347
            ->canBeEnabled()
348
                ->children()
349
                    ->scalarNode('journal')
350 2
                        ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
351
                        ->isRequired()
352 2
                        ->cannotBeEmpty()
353 2
                    ->end()
354 2
                ->end()
355 2
            ->end();
356
        // End history plugin
357 2
358 1
        $logger = $children->arrayNode('logger');
359
        $disableAll ?  $logger->canBeEnabled() : $logger->canBeDisabled();
360
        $logger->addDefaultsIfNotSet()
361 1
            ->children()
362 1
                ->scalarNode('logger')
363 1
                    ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
364 1
                    ->defaultValue('logger')
365 1
                    ->cannotBeEmpty()
366 1
                ->end()
367
                ->scalarNode('formatter')
368
                    ->info('This must be a service id to a service implementing Http\Message\Formatter')
369
                    ->defaultNull()
370
                ->end()
371
            ->end()
372
        ->end();
373
        // End logger plugin
374
375
        $redirect = $children->arrayNode('redirect');
376
        $disableAll ? $redirect->canBeEnabled() : $redirect->canBeDisabled();
377
        $redirect->addDefaultsIfNotSet()
378
            ->children()
379
                ->scalarNode('preserve_header')->defaultTrue()->end()
380
                ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
381
            ->end()
382
        ->end();
383
        // End redirect plugin
384
385
        $retry = $children->arrayNode('retry');
386
        $disableAll ? $retry->canBeEnabled() : $retry->canBeDisabled();
387
        $retry->addDefaultsIfNotSet()
388
            ->children()
389
                ->scalarNode('retry')->defaultValue(1)->end() // TODO: should be called retries for consistency with the class
390
            ->end()
391
        ->end();
392
        // End retry plugin
393
394
        $stopwatch = $children->arrayNode('stopwatch');
395
        $disableAll ? $stopwatch->canBeEnabled() : $stopwatch->canBeDisabled();
396
        $stopwatch->addDefaultsIfNotSet()
397
            ->children()
398
                ->scalarNode('stopwatch')
399
                    ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
400
                    ->defaultValue('debug.stopwatch')
401
                    ->cannotBeEmpty()
402
                ->end()
403
            ->end()
404
        ->end();
405
        // End stopwatch plugin
406
    }
407
408
    /**
409
     * Create configuration for authentication plugin.
410
     *
411
     * @return NodeDefinition Definition for the authentication node in the plugins list.
412
     */
413
    private function createAuthenticationPluginNode()
414
    {
415
        $builder = new TreeBuilder();
416
        $node = $builder->root('authentication');
417
        $node
418
            ->useAttributeAsKey('name')
419
            ->prototype('array')
420
                ->validate()
421
                    ->always()
422
                    ->then(function ($config) {
423
                        switch ($config['type']) {
424
                            case 'basic':
425
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
426
                                break;
427
                            case 'bearer':
428
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
429
                                break;
430
                            case 'service':
431
                                $this->validateAuthenticationType(['service'], $config, 'service');
432
                                break;
433
                            case 'wsse':
434
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
435
                                break;
436
                        }
437
438
                        return $config;
439
                    })
440
                ->end()
441
                ->children()
442
                    ->enumNode('type')
443
                        ->values(['basic', 'bearer', 'wsse', 'service'])
444
                        ->isRequired()
445
                        ->cannotBeEmpty()
446
                    ->end()
447
                    ->scalarNode('username')->end()
448
                    ->scalarNode('password')->end()
449
                    ->scalarNode('token')->end()
450
                    ->scalarNode('service')->end()
451
                    ->end()
452
                ->end()
453
            ->end(); // End authentication plugin
454
455
        return $node;
456
    }
457
458
    /**
459
     * Validate that the configuration fragment has the specified keys and none other.
460
     *
461
     * @param array  $expected Fields that must exist
462
     * @param array  $actual   Actual configuration hashmap
463
     * @param string $authName Name of authentication method for error messages
464
     *
465
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
466
     */
467
    private function validateAuthenticationType(array $expected, array $actual, $authName)
468
    {
469
        unset($actual['type']);
470
        $actual = array_keys($actual);
471
        sort($actual);
472
        sort($expected);
473
474
        if ($expected === $actual) {
475
            return;
476
        }
477
478
        throw new InvalidConfigurationException(sprintf(
479
            'Authentication "%s" requires %s but got %s',
480
            $authName,
481
            implode(', ', $expected),
482
            implode(', ', $actual)
483
        ));
484
    }
485
}
486