Completed
Push — master ( 4408c9...ec48ab )
by Tobias
10s
created

Configuration::configureClients()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 42
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 36
CRAP Score 2.0005

Importance

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