Completed
Pull Request — master (#127)
by Pascal
08:48
created

Configuration   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 524
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 99.5%

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 5
dl 0
loc 524
ccs 395
cts 397
cp 0.995
rs 9
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C getConfigTreeBuilder() 0 111 12
B configureClients() 0 41 2
A configureSharedPlugins() 0 11 1
B createClientPluginNode() 0 129 6
B addSharedPluginNodes() 0 113 6
B createAuthenticationPluginNode() 0 44 5
A validateAuthenticationType() 0 18 2
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
        $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
                    ->append($this->createClientPluginNode())
191 16
                ->end()
192 16
            ->end()
193 16
        ->end();
194 16
    }
195
196
    /**
197
     * @param ArrayNodeDefinition $root
198
     */
199 16
    private function configureSharedPlugins(ArrayNodeDefinition $root)
200
    {
201
        $pluginsNode = $root
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method addDefaultsIfNotSet() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
202 16
            ->children()
203 16
                ->arrayNode('plugins')
204 16
                ->info('Global plugin configuration. Plugins need to be explicitly added to clients.')
205 16
                ->addDefaultsIfNotSet()
206
            // don't call end to get the plugins node
207 16
        ;
208 16
        $this->addSharedPluginNodes($pluginsNode);
209 16
    }
210
211
    /**
212
     * Createplugins node of a client.
213
     *
214
     * @return ArrayNodeDefinition The plugin node
215
     */
216 16
    private function createClientPluginNode()
217
    {
218 16
        $builder = new TreeBuilder();
219 16
        $node = $builder->root('plugins');
220
221
        /** @var ArrayNodeDefinition $pluginList */
222
        $pluginList = $node
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method prototype() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
223 16
            ->info('A list of plugin service ids and client specific plugin definitions. The order is important.')
224 16
            ->prototype('array')
225 16
        ;
226
        $pluginList
227
            // support having just a service id in the list
228 16
            ->beforeNormalization()
229
                ->always(function ($plugin) {
230 8
                    if (is_string($plugin)) {
231
                        return [
232
                            'reference' => [
233 7
                                'enabled' => true,
234 7
                                'id' => $plugin,
235 7
                            ],
236 7
                        ];
237
                    }
238
239 5
                    return $plugin;
240 16
                })
241 16
            ->end()
242
243 16
            ->validate()
244
                ->always(function ($plugins) {
245 7
                    foreach ($plugins as $name => $definition) {
246 7
                        if ('authentication' === $name) {
247 7
                            if (!count($definition)) {
248 7
                                unset($plugins['authentication']);
249 7
                            }
250 7
                        } elseif (!$definition['enabled']) {
251 7
                            unset($plugins[$name]);
252 7
                        }
253 7
                    }
254
255 7
                    return $plugins;
256 16
                })
257 16
            ->end()
258
        ;
259 16
        $this->addSharedPluginNodes($pluginList, true);
260
261
        $pluginList
262 16
            ->children()
263 16
                ->arrayNode('reference')
264 16
                    ->canBeEnabled()
265 16
                    ->info('Reference to a plugin service')
266 16
                    ->children()
267 16
                        ->scalarNode('id')
268 16
                            ->info('Service id of a plugin')
269 16
                            ->isRequired()
270 16
                            ->cannotBeEmpty()
271 16
                        ->end()
272 16
                    ->end()
273 16
                ->end()
274 16
                ->arrayNode('add_host')
275 16
                    ->canBeEnabled()
276 16
                    ->addDefaultsIfNotSet()
277 16
                    ->info('Set scheme, host and port in the request URI.')
278 16
                    ->children()
279 16
                        ->scalarNode('host')
280 16
                            ->info('Host name including protocol and optionally the port number, e.g. https://api.local:8000')
281 16
                            ->isRequired()
282 16
                            ->cannotBeEmpty()
283 16
                        ->end()
284 16
                        ->scalarNode('replace')
285 16
                            ->info('Whether to replace the host if request already specifies one')
286 16
                            ->defaultValue(false)
287 16
                        ->end()
288 16
                    ->end()
289 16
                ->end()
290 16
                ->arrayNode('header_append')
291 16
                    ->canBeEnabled()
292 16
                    ->info('Append headers to the request. If the header already exists the value will be appended to the current value.')
293 16
                    ->fixXmlConfig('header')
294 16
                    ->children()
295 16
                        ->arrayNode('headers')
296 16
                            ->info('Keys are the header names, values the header values')
297 16
                            ->normalizeKeys(false)
298 16
                            ->useAttributeAsKey('name')
299 16
                            ->prototype('scalar')->end()
300 16
                        ->end()
301 16
                    ->end()
302 16
                ->end()
303 16
                ->arrayNode('header_defaults')
304 16
                    ->canBeEnabled()
305 16
                    ->info('Set header to default value if it does not exist.')
306 16
                    ->fixXmlConfig('header')
307 16
                    ->children()
308 16
                        ->arrayNode('headers')
309 16
                            ->info('Keys are the header names, values the header values')
310 16
                            ->normalizeKeys(false)
311 16
                            ->useAttributeAsKey('name')
312 16
                            ->prototype('scalar')->end()
313 16
                        ->end()
314 16
                    ->end()
315 16
                ->end()
316 16
                ->arrayNode('header_set')
317 16
                    ->canBeEnabled()
318 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.')
319 16
                    ->fixXmlConfig('header')
320 16
                    ->children()
321 16
                        ->arrayNode('headers')
322 16
                            ->info('Keys are the header names, values the header values')
323 16
                            ->normalizeKeys(false)
324 16
                            ->useAttributeAsKey('name')
325 16
                            ->prototype('scalar')->end()
326 16
                        ->end()
327 16
                    ->end()
328 16
                ->end()
329 16
                ->arrayNode('header_remove')
330 16
                    ->canBeEnabled()
331 16
                    ->info('Remove headers from requests.')
332 16
                    ->fixXmlConfig('header')
333 16
                    ->children()
334 16
                        ->arrayNode('headers')
335 16
                            ->info('List of header names to remove')
336 16
                            ->prototype('scalar')->end()
337 16
                        ->end()
338 16
                    ->end()
339 16
                ->end()
340 16
            ->end()
341 16
        ->end();
342
343 16
        return $node;
344
    }
345
346
    /**
347
     * Add the definitions for shared plugin configurations.
348
     *
349
     * @param ArrayNodeDefinition $pluginNode The node to add to.
350
     * @param bool                $disableAll Some shared plugins are enabled by default. On the client, all are disabled by default.
351
     */
352 16
    private function addSharedPluginNodes(ArrayNodeDefinition $pluginNode, $disableAll = false)
353
    {
354 16
        $children = $pluginNode->children();
355
356 16
        $children->append($this->createAuthenticationPluginNode());
357
358 16
        $children->arrayNode('cache')
359 16
            ->canBeEnabled()
360 16
            ->addDefaultsIfNotSet()
361 16
                ->children()
362 16
                    ->scalarNode('cache_pool')
363 16
                        ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
364 16
                        ->isRequired()
365 16
                        ->cannotBeEmpty()
366 16
                    ->end()
367 16
                    ->scalarNode('stream_factory')
368 16
                        ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
369 16
                        ->defaultValue('httplug.stream_factory')
370 16
                        ->cannotBeEmpty()
371 16
                    ->end()
372 16
                    ->arrayNode('config')
373 16
                        ->addDefaultsIfNotSet()
374 16
                        ->children()
375 16
                            ->scalarNode('default_ttl')->defaultNull()->end()
376 16
                            ->scalarNode('respect_cache_headers')->defaultTrue()->end()
377 16
                        ->end()
378 16
                    ->end()
379 16
                ->end()
380 16
            ->end();
381
        // End cache plugin
382
383 16
        $children->arrayNode('cookie')
384 16
            ->canBeEnabled()
385 16
                ->children()
386 16
                    ->scalarNode('cookie_jar')
387 16
                        ->info('This must be a service id to a service implementing Http\Message\CookieJar')
388 16
                        ->isRequired()
389 16
                        ->cannotBeEmpty()
390 16
                    ->end()
391 16
                ->end()
392 16
            ->end();
393
        // End cookie plugin
394
395 16
        $decoder = $children->arrayNode('decoder');
396 16
        $disableAll ? $decoder->canBeEnabled() : $decoder->canBeDisabled();
397 16
        $decoder->addDefaultsIfNotSet()
398 16
            ->children()
399 16
                ->scalarNode('use_content_encoding')->defaultTrue()->end()
400 16
            ->end()
401 16
        ->end();
402
        // End decoder plugin
403
404 16
        $children->arrayNode('history')
405 16
            ->canBeEnabled()
406 16
                ->children()
407 16
                    ->scalarNode('journal')
408 16
                        ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
409 16
                        ->isRequired()
410 16
                        ->cannotBeEmpty()
411 16
                    ->end()
412 16
                ->end()
413 16
            ->end();
414
        // End history plugin
415
416 16
        $logger = $children->arrayNode('logger');
417 16
        $disableAll ? $logger->canBeEnabled() : $logger->canBeDisabled();
418 16
        $logger->addDefaultsIfNotSet()
419 16
            ->children()
420 16
                ->scalarNode('logger')
421 16
                    ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
422 16
                    ->defaultValue('logger')
423 16
                    ->cannotBeEmpty()
424 16
                ->end()
425 16
                ->scalarNode('formatter')
426 16
                    ->info('This must be a service id to a service implementing Http\Message\Formatter')
427 16
                    ->defaultNull()
428 16
                ->end()
429 16
            ->end()
430 16
        ->end();
431
        // End logger plugin
432
433 16
        $redirect = $children->arrayNode('redirect');
434 16
        $disableAll ? $redirect->canBeEnabled() : $redirect->canBeDisabled();
435 16
        $redirect->addDefaultsIfNotSet()
436 16
            ->children()
437 16
                ->scalarNode('preserve_header')->defaultTrue()->end()
438 16
                ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
439 16
            ->end()
440 16
        ->end();
441
        // End redirect plugin
442
443 16
        $retry = $children->arrayNode('retry');
444 16
        $disableAll ? $retry->canBeEnabled() : $retry->canBeDisabled();
445 16
        $retry->addDefaultsIfNotSet()
446 16
            ->children()
447 16
                ->scalarNode('retry')->defaultValue(1)->end() // TODO: should be called retries for consistency with the class
448 16
            ->end()
449 16
        ->end();
450
        // End retry plugin
451
452 16
        $stopwatch = $children->arrayNode('stopwatch');
453 16
        $disableAll ? $stopwatch->canBeEnabled() : $stopwatch->canBeDisabled();
454 16
        $stopwatch->addDefaultsIfNotSet()
455 16
            ->children()
456 16
                ->scalarNode('stopwatch')
457 16
                    ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
458 16
                    ->defaultValue('debug.stopwatch')
459 16
                    ->cannotBeEmpty()
460 16
                ->end()
461 16
            ->end()
462 16
        ->end();
463
        // End stopwatch plugin
464 16
    }
465
466
    /**
467
     * Create configuration for authentication plugin.
468
     *
469
     * @return NodeDefinition Definition for the authentication node in the plugins list.
470
     */
471 16
    private function createAuthenticationPluginNode()
472
    {
473 16
        $builder = new TreeBuilder();
474 16
        $node = $builder->root('authentication');
475
        $node
476 16
            ->useAttributeAsKey('name')
477 16
            ->prototype('array')
478 16
                ->validate()
479 16
                    ->always()
480 16
                    ->then(function ($config) {
481 5
                        switch ($config['type']) {
482 5
                            case 'basic':
483 4
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
484 4
                                break;
485 2
                            case 'bearer':
486 1
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
487 1
                                break;
488 2
                            case 'service':
489 2
                                $this->validateAuthenticationType(['service'], $config, 'service');
490 1
                                break;
491 1
                            case 'wsse':
492 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
493 1
                                break;
494 4
                        }
495
496 4
                        return $config;
497 16
                    })
498 16
                ->end()
499 16
                ->children()
500 16
                    ->enumNode('type')
501 16
                        ->values(['basic', 'bearer', 'wsse', 'service'])
502 16
                        ->isRequired()
503 16
                        ->cannotBeEmpty()
504 16
                    ->end()
505 16
                    ->scalarNode('username')->end()
506 16
                    ->scalarNode('password')->end()
507 16
                    ->scalarNode('token')->end()
508 16
                    ->scalarNode('service')->end()
509 16
                    ->end()
510 16
                ->end()
511 16
            ->end(); // End authentication plugin
512
513 16
        return $node;
514
    }
515
516
    /**
517
     * Validate that the configuration fragment has the specified keys and none other.
518
     *
519
     * @param array  $expected Fields that must exist
520
     * @param array  $actual   Actual configuration hashmap
521
     * @param string $authName Name of authentication method for error messages
522
     *
523
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
524
     */
525 5
    private function validateAuthenticationType(array $expected, array $actual, $authName)
526
    {
527 5
        unset($actual['type']);
528 5
        $actual = array_keys($actual);
529 5
        sort($actual);
530 5
        sort($expected);
531
532 5
        if ($expected === $actual) {
533 4
            return;
534
        }
535
536 1
        throw new InvalidConfigurationException(sprintf(
537 1
            'Authentication "%s" requires %s but got %s',
538 1
            $authName,
539 1
            implode(', ', $expected),
540 1
            implode(', ', $actual)
541 1
        ));
542
    }
543
}
544