Completed
Pull Request — master (#112)
by David
07:41 queued 04:44
created

Configuration::configurePlugins()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 111
Code Lines 100

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 101
CRAP Score 1

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 111
ccs 101
cts 101
cp 1
rs 8.2857
cc 1
eloc 100
nc 1
nop 1
crap 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A Configuration::configureSharedPlugins() 0 10 1

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\NodeDefinition;
7
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
8
use Symfony\Component\Config\Definition\ConfigurationInterface;
9
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
10
11
/**
12
 * This class contains the configuration information for the bundle.
13
 *
14
 * This information is solely responsible for how the different configuration
15
 * sections are normalized, and merged.
16
 *
17
 * @author David Buchmann <[email protected]>
18
 * @author Tobias Nyholm <[email protected]>
19
 */
20
class Configuration implements ConfigurationInterface
21
{
22
    /**
23
     * Whether to use the debug mode.
24
     *
25
     * @see https://github.com/doctrine/DoctrineBundle/blob/v1.5.2/DependencyInjection/Configuration.php#L31-L41
26
     *
27
     * @var bool
28
     */
29
    private $debug;
30
31
    /**
32
     * @param bool $debug
33
     */
34 16
    public function __construct($debug)
35
    {
36 16
        $this->debug = (bool) $debug;
37 16
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 16
    public function getConfigTreeBuilder()
43
    {
44 16
        $treeBuilder = new TreeBuilder();
45 16
        $rootNode = $treeBuilder->root('httplug');
46
47 16
        $this->configureClients($rootNode);
48 16
        $this->configureSharedPlugins($rootNode);
49
50
        $rootNode
51 16
            ->validate()
52
                ->ifTrue(function ($v) {
53 13
                    return !empty($v['classes']['client'])
54 13
                        || !empty($v['classes']['message_factory'])
55 10
                        || !empty($v['classes']['uri_factory'])
56 13
                        || !empty($v['classes']['stream_factory']);
57 16
                })
58
                ->then(function ($v) {
59 3
                    foreach ($v['classes'] as $key => $class) {
60 3
                        if (null !== $class && !class_exists($class)) {
61 1
                            throw new InvalidConfigurationException(sprintf(
62 1
                                'Class %s specified for httplug.classes.%s does not exist.',
63 1
                                $class,
64
                                $key
65 1
                            ));
66
                        }
67 2
                    }
68
69 2
                    return $v;
70 16
                })
71 16
            ->end()
72 16
            ->beforeNormalization()
73
                ->ifTrue(function ($v) {
74 16
                    return is_array($v) && array_key_exists('toolbar', $v) && is_array($v['toolbar']);
75 16
                })
76
                ->then(function ($v) {
77 4
                    if (array_key_exists('profiling', $v)) {
78 1
                        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".');
79
                    }
80
81 3
                    @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...
82
83 3
                    if (array_key_exists('enabled', $v['toolbar']) && 'auto' === $v['toolbar']['enabled']) {
84 1
                        @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...
85 1
                        $v['toolbar']['enabled'] = $this->debug;
86 1
                    }
87
88 3
                    $v['profiling'] = $v['toolbar'];
89
90 3
                    unset($v['toolbar']);
91
92 3
                    return $v;
93 16
                })
94 16
            ->end()
95 16
            ->fixXmlConfig('client')
96 16
            ->children()
97 16
                ->arrayNode('main_alias')
98 16
                    ->addDefaultsIfNotSet()
99 16
                    ->info('Configure which service the main alias point to.')
100 16
                    ->children()
101 16
                        ->scalarNode('client')->defaultValue('httplug.client.default')->end()
102 16
                        ->scalarNode('message_factory')->defaultValue('httplug.message_factory.default')->end()
103 16
                        ->scalarNode('uri_factory')->defaultValue('httplug.uri_factory.default')->end()
104 16
                        ->scalarNode('stream_factory')->defaultValue('httplug.stream_factory.default')->end()
105 16
                    ->end()
106 16
                ->end()
107 16
                ->arrayNode('classes')
108 16
                    ->addDefaultsIfNotSet()
109 16
                    ->info('Overwrite a service class instead of using the discovery mechanism.')
110 16
                    ->children()
111 16
                        ->scalarNode('client')->defaultNull()->end()
112 16
                        ->scalarNode('message_factory')->defaultNull()->end()
113 16
                        ->scalarNode('uri_factory')->defaultNull()->end()
114 16
                        ->scalarNode('stream_factory')->defaultNull()->end()
115 16
                    ->end()
116 16
                ->end()
117 16
                ->arrayNode('profiling')
118 16
                    ->addDefaultsIfNotSet()
119 16
                    ->treatFalseLike(['enabled' => false])
120 16
                    ->treatTrueLike(['enabled' => true])
121 16
                    ->treatNullLike(['enabled' => $this->debug])
122 16
                    ->info('Extend the debug profiler with information about requests.')
123 16
                    ->children()
124 16
                        ->booleanNode('enabled')
125 16
                            ->info('Turn the toolbar on or off. Defaults to kernel debug mode.')
126 16
                            ->defaultValue($this->debug)
127 16
                        ->end()
128 16
                        ->scalarNode('formatter')->defaultNull()->end()
129 16
                        ->integerNode('captured_body_length')
130 16
                            ->defaultValue(0)
131 16
                            ->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).')
132 16
                        ->end()
133 16
                    ->end()
134 16
                ->end()
135 16
                ->arrayNode('discovery')
136 16
                    ->addDefaultsIfNotSet()
137 16
                    ->info('Control what clients should be found by the discovery.')
138 16
                    ->children()
139 16
                        ->scalarNode('client')
140 16
                            ->defaultValue('auto')
141 16
                            ->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.')
142 16
                        ->end()
143 16
                        ->scalarNode('async_client')
144 16
                            ->defaultNull()
145 16
                            ->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.')
146 16
                        ->end()
147 16
                    ->end()
148 16
                ->end()
149 16
            ->end();
150
151 16
        return $treeBuilder;
152
    }
153
154 16
    private function configureClients(ArrayNodeDefinition $root)
155
    {
156 16
        $pluginNode = $root->children()
157 16
            ->arrayNode('clients')
158 16
                ->validate()
159
                    ->ifTrue(function ($clients) {
160 7
                        foreach ($clients as $name => $config) {
161
                            // Make sure we only allow one of these to be true
162 7
                            return (bool) $config['flexible_client'] + (bool) $config['http_methods_client'] + (bool) $config['batch_client'] >= 2;
163
                        }
164
165
                        return false;
166 16
                    })
167 16
                    ->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()
168 16
                ->useAttributeAsKey('name')
169 16
                ->prototype('array')
170 16
                ->fixXmlConfig('plugin')
171 16
                ->children()
172 16
                    ->scalarNode('factory')
173 16
                        ->isRequired()
174 16
                        ->cannotBeEmpty()
175 16
                        ->info('The service id of a factory to use when creating the adapter.')
176 16
                    ->end()
177 16
                    ->booleanNode('flexible_client')
178 16
                        ->defaultFalse()
179 16
                        ->info('Set to true to get the client wrapped in a FlexibleHttpClient which emulates async or sync behavior.')
180 16
                    ->end()
181 16
                    ->booleanNode('http_methods_client')
182 16
                        ->defaultFalse()
183 16
                        ->info('Set to true to get the client wrapped in a HttpMethodsClient which emulates provides functions for HTTP verbs.')
184 16
                    ->end()
185 16
                    ->booleanNode('batch_client')
186 16
                        ->defaultFalse()
187 16
                        ->info('Set to true to get the client wrapped in a BatchClient which allows you to send multiple request at the same time.')
188 16
                    ->end()
189 16
                    ->variableNode('config')->defaultValue([])->end()
190 16
                    ->arrayNode('plugins')
191 16
                        ->info('A list of plugin service ids and client specific plugin definitions. The order is important.')
192 16
                        ->prototype('array')
193 16
        ;
194
195 16
        $this->configureClientPlugins($pluginNode);
196 16
    }
197
198
    /**
199
     * @param ArrayNodeDefinition $root
200
     */
201 16
    private function configureSharedPlugins(ArrayNodeDefinition $root)
202
    {
203
        $pluginsNode = $root
204 16
            ->children()
205 16
                ->arrayNode('plugins')
206 16
                ->info('Global plugin configuration. Plugins need to be explicitly added to clients.')
207 16
                ->addDefaultsIfNotSet()
208 16
        ;
209 16
        $this->addSharedPluginNodes($pluginsNode);
210 16
    }
211
212
    /**
213
     * Configure plugins node of a client.
214
     *
215
     * @param ArrayNodeDefinition $pluginNode The node to add plugin definitions to.
216
     */
217 16
    private function configureClientPlugins(ArrayNodeDefinition $pluginNode)
218
    {
219
        $pluginNode
220
            // support having just a service id in the list
221 16
            ->beforeNormalization()
222
                ->always(function ($plugin) {
223 8
                    if (is_string($plugin)) {
224
                        return [
225
                            'reference' => [
226 7
                                'enabled' => true,
227 7
                                'id' => $plugin,
228 7
                            ],
229 7
                        ];
230
                    }
231
232 5
                    return $plugin;
233 16
                })
234 16
            ->end()
235
236 16
            ->validate()
237
                ->always(function ($plugins) {
238 7
                    foreach ($plugins as $name => $definition) {
239 7
                        if ('authentication' === $name) {
240 7
                            if (!count($definition)) {
241 7
                                unset($plugins['authentication']);
242 7
                            }
243 7
                        } elseif (!$definition['enabled']) {
244 7
                            unset($plugins[$name]);
245 7
                        }
246 7
                    }
247
248 7
                    return $plugins;
249 16
                })
250 16
            ->end()
251
        ;
252 16
        $this->addSharedPluginNodes($pluginNode, true);
253
254
        $pluginNode
255 16
            ->children()
256 16
                ->arrayNode('reference')
257 16
                    ->canBeEnabled()
258 16
                    ->info('Reference to a plugin service')
259 16
                    ->children()
260 16
                        ->scalarNode('id')
261 16
                            ->info('Service id of a plugin')
262 16
                            ->isRequired()
263 16
                            ->cannotBeEmpty()
264 16
                        ->end()
265 16
                    ->end()
266 16
                ->end()
267 16
                ->arrayNode('add_host')
268 16
                    ->canBeEnabled()
269 16
                    ->addDefaultsIfNotSet()
270 16
                    ->info('Configure the AddHostPlugin for this client.')
271 16
                    ->children()
272 16
                        ->scalarNode('host')
273 16
                            ->info('Host name including protocol and optionally the port number, e.g. https://api.local:8000')
274 16
                            ->isRequired()
275 16
                            ->cannotBeEmpty()
276 16
                        ->end()
277 16
                        ->scalarNode('replace')
278 16
                            ->info('Whether to replace the host if request already specifies it')
279 16
                            ->defaultValue(false)
280 16
                        ->end()
281 16
                    ->end()
282 16
                ->end()
283 16
                ->arrayNode('header_append')
284 16
                    ->canBeEnabled()
285 16
                    ->info('Append headers to the request. If the header already exists the value will be appended to the current value.')
286 16
                    ->fixXmlConfig('header')
287 16
                    ->children()
288 16
                        ->arrayNode('headers')
289 16
                            ->info('Keys are the header names, values the header values')
290 16
                            ->normalizeKeys(false)
291 16
                            ->useAttributeAsKey('name')
292 16
                            ->prototype('scalar')->end()
293 16
                        ->end()
294 16
                    ->end()
295 16
                ->end()
296 16
                ->arrayNode('header_defaults')
297 16
                    ->canBeEnabled()
298 16
                    ->info('Set header to default value if it does not exist.')
299 16
                    ->fixXmlConfig('header')
300 16
                    ->children()
301 16
                        ->arrayNode('headers')
302 16
                            ->info('Keys are the header names, values the header values')
303 16
                            ->normalizeKeys(false)
304 16
                            ->useAttributeAsKey('name')
305 16
                            ->prototype('scalar')->end()
306 16
                        ->end()
307 16
                    ->end()
308 16
                ->end()
309 16
                ->arrayNode('header_set')
310 16
                    ->canBeEnabled()
311 16
                    ->info('Set headers to requests. If the header does not exist it wil be set, if the header already exists it will be replaced.')
312 16
                    ->fixXmlConfig('header')
313 16
                    ->children()
314 16
                        ->arrayNode('headers')
315 16
                            ->info('Keys are the header names, values the header values')
316 16
                            ->normalizeKeys(false)
317 16
                            ->useAttributeAsKey('name')
318 16
                            ->prototype('scalar')->end()
319 16
                        ->end()
320 16
                    ->end()
321 16
                ->end()
322 16
                ->arrayNode('header_remove')
323 16
                    ->canBeEnabled()
324 16
                    ->info('Remove headers from requests.')
325 16
                    ->fixXmlConfig('header')
326 16
                    ->children()
327 16
                        ->arrayNode('headers')
328 16
                            ->info('List of header names to remove')
329 16
                            ->prototype('scalar')->end()
330 16
                        ->end()
331 16
                    ->end()
332 16
                ->end()
333 16
            ->end()
334 16
        ->end();
335 16
    }
336
337
    /**
338
     * Add the definitions for shared plugin configurations.
339
     *
340
     * @param ArrayNodeDefinition $pluginNode The node to add to.
341
     * @param bool                $disableAll Some shared plugins are enabled by default. On the client, all are disabled by default.
342
     */
343 16
    private function addSharedPluginNodes(ArrayNodeDefinition $pluginNode, $disableAll = false)
344
    {
345 16
        $children = $pluginNode->children();
346
347 16
        $children->append($this->createAuthenticationPluginNode());
348
349 16
        $children->arrayNode('cache')
350 16
            ->canBeEnabled()
351 16
            ->addDefaultsIfNotSet()
352 16
                ->children()
353 16
                    ->scalarNode('cache_pool')
354 16
                        ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
355 16
                        ->isRequired()
356 16
                        ->cannotBeEmpty()
357 16
                    ->end()
358 16
                    ->scalarNode('stream_factory')
359 16
                        ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
360 16
                        ->defaultValue('httplug.stream_factory')
361 16
                        ->cannotBeEmpty()
362 16
                    ->end()
363 16
                    ->arrayNode('config')
364 16
                        ->addDefaultsIfNotSet()
365 16
                        ->children()
366 16
                            ->scalarNode('default_ttl')->defaultNull()->end()
367 16
                            ->scalarNode('respect_cache_headers')->defaultTrue()->end()
368 16
                        ->end()
369 16
                    ->end()
370 16
                ->end()
371 16
            ->end();
372
        // End cache plugin
373
374 16
        $children->arrayNode('cookie')
375 16
            ->canBeEnabled()
376 16
                ->children()
377 16
                    ->scalarNode('cookie_jar')
378 16
                        ->info('This must be a service id to a service implementing Http\Message\CookieJar')
379 16
                        ->isRequired()
380 16
                        ->cannotBeEmpty()
381 16
                    ->end()
382 16
                ->end()
383 16
            ->end();
384
        // End cookie plugin
385
386 16
        $decoder = $children->arrayNode('decoder');
387 16
        $disableAll ? $decoder->canBeEnabled() : $decoder->canBeDisabled();
388 16
        $decoder->addDefaultsIfNotSet()
389 16
            ->children()
390 16
                ->scalarNode('use_content_encoding')->defaultTrue()->end()
391 16
            ->end()
392 16
        ->end();
393
        // End decoder plugin
394
395 16
        $children->arrayNode('history')
396 16
            ->canBeEnabled()
397 16
                ->children()
398 16
                    ->scalarNode('journal')
399 16
                        ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
400 16
                        ->isRequired()
401 16
                        ->cannotBeEmpty()
402 16
                    ->end()
403 16
                ->end()
404 16
            ->end();
405
        // End history plugin
406
407 16
        $logger = $children->arrayNode('logger');
408 16
        $disableAll ? $logger->canBeEnabled() : $logger->canBeDisabled();
409 16
        $logger->addDefaultsIfNotSet()
410 16
            ->children()
411 16
                ->scalarNode('logger')
412 16
                    ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
413 16
                    ->defaultValue('logger')
414 16
                    ->cannotBeEmpty()
415 16
                ->end()
416 16
                ->scalarNode('formatter')
417 16
                    ->info('This must be a service id to a service implementing Http\Message\Formatter')
418 16
                    ->defaultNull()
419 16
                ->end()
420 16
            ->end()
421 16
        ->end();
422
        // End logger plugin
423
424 16
        $redirect = $children->arrayNode('redirect');
425 16
        $disableAll ? $redirect->canBeEnabled() : $redirect->canBeDisabled();
426 16
        $redirect->addDefaultsIfNotSet()
427 16
            ->children()
428 16
                ->scalarNode('preserve_header')->defaultTrue()->end()
429 16
                ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
430 16
            ->end()
431 16
        ->end();
432
        // End redirect plugin
433
434 16
        $retry = $children->arrayNode('retry');
435 16
        $disableAll ? $retry->canBeEnabled() : $retry->canBeDisabled();
436 16
        $retry->addDefaultsIfNotSet()
437 16
            ->children()
438 16
                ->scalarNode('retry')->defaultValue(1)->end() // TODO: should be called retries for consistency with the class
439 16
            ->end()
440 16
        ->end();
441
        // End retry plugin
442
443 16
        $stopwatch = $children->arrayNode('stopwatch');
444 16
        $disableAll ? $stopwatch->canBeEnabled() : $stopwatch->canBeDisabled();
445 16
        $stopwatch->addDefaultsIfNotSet()
446 16
            ->children()
447 16
                ->scalarNode('stopwatch')
448 16
                    ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
449 16
                    ->defaultValue('debug.stopwatch')
450 16
                    ->cannotBeEmpty()
451 16
                ->end()
452 16
            ->end()
453 16
        ->end();
454
        // End stopwatch plugin
455 16
    }
456
457
    /**
458
     * Create configuration for authentication plugin.
459
     *
460
     * @return NodeDefinition Definition for the authentication node in the plugins list.
461
     */
462 16
    private function createAuthenticationPluginNode()
463
    {
464 16
        $builder = new TreeBuilder();
465 16
        $node = $builder->root('authentication');
466
        $node
467 16
            ->useAttributeAsKey('name')
468 16
            ->prototype('array')
469 16
                ->validate()
470 16
                    ->always()
471 16
                    ->then(function ($config) {
472 5
                        switch ($config['type']) {
473 5
                            case 'basic':
474 4
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
475 4
                                break;
476 2
                            case 'bearer':
477 1
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
478 1
                                break;
479 2
                            case 'service':
480 2
                                $this->validateAuthenticationType(['service'], $config, 'service');
481 1
                                break;
482 1
                            case 'wsse':
483 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
484 1
                                break;
485 4
                        }
486
487 4
                        return $config;
488 16
                    })
489 16
                ->end()
490 16
                ->children()
491 16
                    ->enumNode('type')
492 16
                        ->values(['basic', 'bearer', 'wsse', 'service'])
493 16
                        ->isRequired()
494 16
                        ->cannotBeEmpty()
495 16
                    ->end()
496 16
                    ->scalarNode('username')->end()
497 16
                    ->scalarNode('password')->end()
498 16
                    ->scalarNode('token')->end()
499 16
                    ->scalarNode('service')->end()
500 16
                    ->end()
501 16
                ->end()
502 16
            ->end(); // End authentication plugin
503
504 16
        return $node;
505
    }
506
507
    /**
508
     * Validate that the configuration fragment has the specified keys and none other.
509
     *
510
     * @param array  $expected Fields that must exist
511
     * @param array  $actual   Actual configuration hashmap
512
     * @param string $authName Name of authentication method for error messages
513
     *
514
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
515
     */
516 5
    private function validateAuthenticationType(array $expected, array $actual, $authName)
517
    {
518 5
        unset($actual['type']);
519 5
        $actual = array_keys($actual);
520 5
        sort($actual);
521 5
        sort($expected);
522
523 5
        if ($expected === $actual) {
524 4
            return;
525
        }
526
527 1
        throw new InvalidConfigurationException(sprintf(
528 1
            'Authentication "%s" requires %s but got %s',
529 1
            $authName,
530 1
            implode(', ', $expected),
531 1
            implode(', ', $actual)
532 1
        ));
533
    }
534
}
535