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

Configuration::configureClientPlugins()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 70
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 63
CRAP Score 6

Importance

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