Completed
Push — master ( d42d86...ba3eee )
by David
08:38
created

Configuration::validateAuthenticationType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 9.4285
cc 2
eloc 12
nc 2
nop 3
crap 2
1
<?php
2
3
namespace Http\HttplugBundle\DependencyInjection;
4
5
use Symfony\Component\Config\Definition\ArrayNode;
6
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
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->configurePlugins($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
            ->children()
73 12
                ->arrayNode('main_alias')
74 12
                    ->addDefaultsIfNotSet()
75 12
                    ->info('Configure which service the main alias point to.')
76 12
                    ->children()
77 12
                        ->scalarNode('client')->defaultValue('httplug.client.default')->end()
78 12
                        ->scalarNode('message_factory')->defaultValue('httplug.message_factory.default')->end()
79 12
                        ->scalarNode('uri_factory')->defaultValue('httplug.uri_factory.default')->end()
80 12
                        ->scalarNode('stream_factory')->defaultValue('httplug.stream_factory.default')->end()
81 12
                    ->end()
82 12
                ->end()
83 12
                ->arrayNode('classes')
84 12
                    ->addDefaultsIfNotSet()
85 12
                    ->info('Overwrite a service class instead of using the discovery mechanism.')
86 12
                    ->children()
87 12
                        ->scalarNode('client')->defaultNull()->end()
88 12
                        ->scalarNode('message_factory')->defaultNull()->end()
89 12
                        ->scalarNode('uri_factory')->defaultNull()->end()
90 12
                        ->scalarNode('stream_factory')->defaultNull()->end()
91 12
                    ->end()
92 12
                ->end()
93 12
                ->arrayNode('toolbar')
94 12
                    ->addDefaultsIfNotSet()
95 12
                    ->info('Extend the debug profiler with information about requests.')
96 12
                    ->children()
97 12
                        ->booleanNode('enabled') // @deprecated value auto in 1.3.0
98 12
                            ->beforeNormalization()
99 12
                                ->ifString()
100
                                ->then(function ($v) {
101 1
                                    return 'auto' === $v ? $this->debug : $v;
102 12
                                })
103 12
                            ->end()
104 12
                            ->info('Turn the toolbar on or off. Defaults to kernel debug mode.')
105 12
                            ->defaultValue($this->debug)
106 12
                        ->end()
107 12
                        ->scalarNode('formatter')->defaultNull()->end()
108 12
                        ->integerNode('captured_body_length')
109 12
                            ->defaultValue(0)
110 12
                            ->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).')
111 12
                        ->end()
112 12
                    ->end()
113 12
                ->end()
114 12
                ->arrayNode('discovery')
115 12
                    ->addDefaultsIfNotSet()
116 12
                    ->info('Control what clients should be found by the discovery.')
117 12
                    ->children()
118 12
                        ->scalarNode('client')
119 12
                            ->defaultValue('auto')
120 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.')
121 12
                        ->end()
122 12
                        ->scalarNode('async_client')
123 12
                            ->defaultNull()
124 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.')
125 12
                        ->end()
126 12
                    ->end()
127 12
                ->end()
128 12
            ->end();
129
130 12
        return $treeBuilder;
131
    }
132
133 12
    protected function configureClients(ArrayNodeDefinition $root)
134
    {
135 12
        $root->children()
136 12
            ->arrayNode('clients')
137 12
                ->validate()
138
                    ->ifTrue(function ($clients) {
139 3
                        foreach ($clients as $name => $config) {
140
                            // Make sure we only allow one of these to be true
141 3
                            return (bool) $config['flexible_client'] + (bool) $config['http_methods_client'] + (bool) $config['batch_client'] >= 2;
142
                        }
143
144
                        return false;
145 12
                    })
146 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()
147 12
                ->useAttributeAsKey('name')
148 12
                ->prototype('array')
149 12
                ->children()
150 12
                    ->scalarNode('factory')
151 12
                        ->isRequired()
152 12
                        ->cannotBeEmpty()
153 12
                        ->info('The service id of a factory to use when creating the adapter.')
154 12
                    ->end()
155 12
                    ->booleanNode('flexible_client')
156 12
                        ->defaultFalse()
157 12
                        ->info('Set to true to get the client wrapped in a FlexibleHttpClient which emulates async or sync behavior.')
158 12
                    ->end()
159 12
                    ->booleanNode('http_methods_client')
160 12
                        ->defaultFalse()
161 12
                        ->info('Set to true to get the client wrapped in a HttpMethodsClient which emulates provides functions for HTTP verbs.')
162 12
                    ->end()
163 12
                    ->booleanNode('batch_client')
164 12
                        ->defaultFalse()
165 12
                        ->info('Set to true to get the client wrapped in a BatchClient which allows you to send multiple request at the same time.')
166 12
                    ->end()
167 12
                    ->arrayNode('plugins')
168 12
                        ->info('A list of service ids of plugins. The order is important.')
169 12
                        ->prototype('scalar')->end()
170 12
                    ->end()
171 12
                    ->variableNode('config')->defaultValue([])->end()
172 12
                ->end()
173 12
            ->end();
174 12
    }
175
176
    /**
177
     * @param ArrayNodeDefinition $root
178
     */
179 12
    protected function configurePlugins(ArrayNodeDefinition $root)
180
    {
181 12
        $root->children()
182 12
            ->arrayNode('plugins')
183 12
                ->addDefaultsIfNotSet()
184 12
                ->children()
185 12
                    ->append($this->addAuthenticationPluiginNode())
186
187 12
                    ->arrayNode('cache')
188 12
                    ->canBeEnabled()
189 12
                    ->addDefaultsIfNotSet()
190 12
                        ->children()
191 12
                            ->scalarNode('cache_pool')
192 12
                                ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
193 12
                                ->isRequired()
194 12
                                ->cannotBeEmpty()
195 12
                            ->end()
196 12
                            ->scalarNode('stream_factory')
197 12
                                ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
198 12
                                ->defaultValue('httplug.stream_factory')
199 12
                                ->cannotBeEmpty()
200 12
                            ->end()
201 12
                            ->arrayNode('config')
202 12
                                ->addDefaultsIfNotSet()
203 12
                                ->children()
204 12
                                    ->scalarNode('default_ttl')->defaultNull()->end()
205 12
                                    ->scalarNode('respect_cache_headers')->defaultTrue()->end()
206 12
                                ->end()
207 12
                            ->end()
208 12
                        ->end()
209 12
                    ->end() // End cache plugin
210
211 12
                    ->arrayNode('cookie')
212 12
                    ->canBeEnabled()
213 12
                        ->children()
214 12
                            ->scalarNode('cookie_jar')
215 12
                                ->info('This must be a service id to a service implementing Http\Message\CookieJar')
216 12
                                ->isRequired()
217 12
                                ->cannotBeEmpty()
218 12
                            ->end()
219 12
                        ->end()
220 12
                    ->end() // End cookie plugin
221
222 12
                    ->arrayNode('decoder')
223 12
                    ->canBeDisabled()
224 12
                    ->addDefaultsIfNotSet()
225 12
                        ->children()
226 12
                            ->scalarNode('use_content_encoding')->defaultTrue()->end()
227 12
                        ->end()
228 12
                    ->end() // End decoder plugin
229
230 12
                    ->arrayNode('history')
231 12
                    ->canBeEnabled()
232 12
                        ->children()
233 12
                            ->scalarNode('journal')
234 12
                                ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
235 12
                                ->isRequired()
236 12
                                ->cannotBeEmpty()
237 12
                            ->end()
238 12
                        ->end()
239 12
                    ->end() // End history plugin
240
241 12
                    ->arrayNode('logger')
242 12
                    ->canBeDisabled()
243 12
                    ->addDefaultsIfNotSet()
244 12
                        ->children()
245 12
                            ->scalarNode('logger')
246 12
                                ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
247 12
                                ->defaultValue('logger')
248 12
                                ->cannotBeEmpty()
249 12
                            ->end()
250 12
                            ->scalarNode('formatter')
251 12
                                ->info('This must be a service id to a service implementing Http\Message\Formatter')
252 12
                                ->defaultNull()
253 12
                            ->end()
254 12
                        ->end()
255 12
                    ->end() // End logger plugin
256
257 12
                    ->arrayNode('redirect')
258 12
                    ->canBeDisabled()
259 12
                    ->addDefaultsIfNotSet()
260 12
                        ->children()
261 12
                            ->scalarNode('preserve_header')->defaultTrue()->end()
262 12
                            ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
263 12
                        ->end()
264 12
                    ->end() // End redirect plugin
265
266 12
                    ->arrayNode('retry')
267 12
                    ->canBeDisabled()
268 12
                    ->addDefaultsIfNotSet()
269 12
                        ->children()
270 12
                            ->scalarNode('retry')->defaultValue(1)->end()
271 12
                        ->end()
272 12
                    ->end() // End retry plugin
273
274 12
                    ->arrayNode('stopwatch')
275 12
                    ->canBeDisabled()
276 12
                    ->addDefaultsIfNotSet()
277 12
                        ->children()
278 12
                            ->scalarNode('stopwatch')
279 12
                                ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
280 12
                                ->defaultValue('debug.stopwatch')
281 12
                                ->cannotBeEmpty()
282 12
                            ->end()
283 12
                        ->end()
284 12
                    ->end() // End stopwatch plugin
285
286 12
                ->end()
287 12
            ->end()
288 12
        ->end();
289 12
    }
290
291
    /**
292
     * Add configuration for authentication plugin.
293
     *
294
     * @return ArrayNodeDefinition|\Symfony\Component\Config\Definition\Builder\NodeDefinition
295
     */
296 12
    private function addAuthenticationPluiginNode()
297
    {
298 12
        $builder = new TreeBuilder();
299 12
        $node = $builder->root('authentication');
300
        $node
301 12
            ->useAttributeAsKey('name')
302 12
            ->prototype('array')
303 12
                ->validate()
304 12
                    ->always()
305 12
                    ->then(function ($config) {
306 2
                        switch ($config['type']) {
307 2
                            case 'basic':
308 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
309 1
                                break;
310 2
                            case 'bearer':
311 1
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
312 1
                                break;
313 2
                            case 'service':
314 2
                                $this->validateAuthenticationType(['service'], $config, 'service');
315 1
                                break;
316 1
                            case 'wsse':
317 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
318 1
                                break;
319 1
                        }
320
321 1
                        return $config;
322 12
                    })
323 12
                ->end()
324 12
                ->children()
325 12
                    ->enumNode('type')
326 12
                        ->values(['basic', 'bearer', 'wsse', 'service'])
327 12
                        ->isRequired()
328 12
                        ->cannotBeEmpty()
329 12
                    ->end()
330 12
                    ->scalarNode('username')->end()
331 12
                    ->scalarNode('password')->end()
332 12
                    ->scalarNode('token')->end()
333 12
                    ->scalarNode('service')->end()
334 12
                    ->end()
335 12
                ->end()
336 12
            ->end(); // End authentication plugin
337
338 12
        return $node;
339
    }
340
341
    /**
342
     * Validate that the configuration fragment has the specified keys and none other.
343
     *
344
     * @param array  $expected Fields that must exist
345
     * @param array  $actual   Actual configuration hashmap
346
     * @param string $authName Name of authentication method for error messages
347
     *
348
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
349
     */
350 2
    private function validateAuthenticationType(array $expected, array $actual, $authName)
351
    {
352 2
        unset($actual['type']);
353 2
        $actual = array_keys($actual);
354 2
        sort($actual);
355 2
        sort($expected);
356
357 2
        if ($expected === $actual) {
358 1
            return;
359
        }
360
361 1
        throw new InvalidConfigurationException(sprintf(
362 1
            'Authentication "%s" requires %s but got %s',
363 1
            $authName,
364 1
            implode(', ', $expected),
365 1
            implode(', ', $actual)
366 1
        ));
367
    }
368
}
369