Completed
Pull Request — master (#87)
by Tobias
08:58
created

Configuration::getConfigTreeBuilder()   C

Complexity

Conditions 7
Paths 1

Size

Total Lines 74
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 60
CRAP Score 7

Importance

Changes 6
Bugs 0 Features 3
Metric Value
c 6
b 0
f 3
dl 0
loc 74
rs 6.6374
ccs 60
cts 60
cp 1
cc 7
eloc 63
nc 1
nop 0
crap 7

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\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
     * {@inheritdoc}
24
     */
25 7
    public function getConfigTreeBuilder()
26
    {
27 7
        $treeBuilder = new TreeBuilder();
28 7
        $rootNode = $treeBuilder->root('httplug');
29
30 7
        $this->configureClients($rootNode);
31 7
        $this->configurePlugins($rootNode);
32
33
        $rootNode
34 7
            ->validate()
35
                ->ifTrue(function ($v) {
36 6
                    return !empty($v['classes']['client'])
37 6
                        || !empty($v['classes']['message_factory'])
38 3
                        || !empty($v['classes']['uri_factory'])
39 6
                        || !empty($v['classes']['stream_factory']);
40 7
                })
41
                ->then(function ($v) {
42 3
                    foreach ($v['classes'] as $key => $class) {
43 3
                        if (null !== $class && !class_exists($class)) {
44 1
                            throw new InvalidConfigurationException(sprintf(
45 1
                                'Class %s specified for httplug.classes.%s does not exist.',
46 1
                                $class,
47
                                $key
48 1
                            ));
49
                        }
50 2
                    }
51
52 2
                    return $v;
53 7
                })
54 7
            ->end()
55 7
            ->children()
56 7
                ->arrayNode('main_alias')
57 7
                    ->addDefaultsIfNotSet()
58 7
                    ->info('Configure which service the main alias point to.')
59 7
                    ->children()
60 7
                        ->scalarNode('client')->defaultValue('httplug.client.default')->end()
61 7
                        ->scalarNode('message_factory')->defaultValue('httplug.message_factory.default')->end()
62 7
                        ->scalarNode('uri_factory')->defaultValue('httplug.uri_factory.default')->end()
63 7
                        ->scalarNode('stream_factory')->defaultValue('httplug.stream_factory.default')->end()
64 7
                    ->end()
65 7
                ->end()
66 7
                ->arrayNode('classes')
67 7
                    ->addDefaultsIfNotSet()
68 7
                    ->info('Overwrite a service class instead of using the discovery mechanism.')
69 7
                    ->children()
70 7
                        ->scalarNode('client')->defaultNull()->end()
71 7
                        ->scalarNode('message_factory')->defaultNull()->end()
72 7
                        ->scalarNode('uri_factory')->defaultNull()->end()
73 7
                        ->scalarNode('stream_factory')->defaultNull()->end()
74 7
                    ->end()
75 7
                ->end()
76 7
                ->arrayNode('toolbar')
77 7
                    ->addDefaultsIfNotSet()
78 7
                    ->info('Extend the debug profiler with inforation about requests.')
79 7
                    ->children()
80 7
                        ->enumNode('enabled')
81 7
                            ->info('If "auto" (default), the toolbar is activated when kernel.debug is true. You can force the toolbar on and off by changing this option.')
82 7
                            ->values([true, false, 'auto'])
83 7
                            ->defaultValue('auto')
84 7
                        ->end()
85 7
                        ->scalarNode('formatter')->defaultNull()->end()
86 7
                        ->booleanNode('inject_debugger_for_discovered_http_client')->defaultTrue()->end()
87 7
                        ->booleanNode('inject_debugger_for_discovered_async_client')->defaultFalse()->end()
88 7
                        ->scalarNode('captured_body_length')
89
                            ->defaultValue(0)
90 7
                            ->canNotBeEmpty()
91
                            ->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).')
92
                        ->end()
93 7
                    ->end()
94
                ->end()
95 7
            ->end();
96 7
97 7
        return $treeBuilder;
98
    }
99
100
    protected function configureClients(ArrayNodeDefinition $root)
101
    {
102
        $root->children()
103
            ->arrayNode('clients')
104 7
                ->validate()
105 7
                    ->ifTrue(function ($clients) {
106 7
                        foreach ($clients as $name => $config) {
107 7
                            return $config['flexible_client'] && $config['http_methods_client'];
108 7
                        }
109 7
110 7
                        return false;
111 7
                    })
112 7
                    ->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()
113 7
                ->useAttributeAsKey('name')
114 7
                ->prototype('array')
115 7
                ->children()
116 7
                    ->scalarNode('factory')
117 7
                        ->isRequired()
118 7
                        ->cannotBeEmpty()
119 7
                        ->info('The service id of a factory to use when creating the adapter.')
120 7
                    ->end()
121 7
                    ->booleanNode('flexible_client')
122 7
                        ->defaultFalse()
123 7
                        ->info('Set to true to get the client wrapped in a FlexibleHttpClient which emulates async or sync behavior.')
124 7
                    ->end()
125 7
                    ->booleanNode('http_methods_client')
126 7
                        ->defaultFalse()
127 7
                        ->info('Set to true to get the client wrapped in a HttpMethodsClient which emulates provides functions for HTTP verbs.')
128 7
                    ->end()
129 7
                    ->enumNode('use_with_discovery')
130
                        ->values(['async_client', 'http_client', false])
131
                        ->defaultFalse()
132
                        ->info('If set to "http_client" this will be the client return when using dicovery to find a HTTP client.')
133
                    ->end()
134 7
                    ->arrayNode('plugins')
135
                        ->info('A list of service ids of plugins. The order is important.')
136 7
                        ->prototype('scalar')->end()
137 7
                    ->end()
138 7
                    ->variableNode('config')->defaultValue([])->end()
139 7
                ->end()
140 7
            ->end();
141
    }
142 7
143 7
    /**
144 7
     * @param ArrayNodeDefinition $root
145 7
     */
146 7
    protected function configurePlugins(ArrayNodeDefinition $root)
147 7
    {
148 7
        $root->children()
149 7
            ->arrayNode('plugins')
150 7
                ->addDefaultsIfNotSet()
151 7
                ->children()
152 7
                    ->append($this->addAuthenticationPluiginNode())
153 7
154 7
                    ->arrayNode('cache')
155 7
                    ->canBeEnabled()
156 7
                    ->addDefaultsIfNotSet()
157 7
                        ->children()
158 7
                            ->scalarNode('cache_pool')
159 7
                                ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
160 7
                                ->isRequired()
161 7
                                ->cannotBeEmpty()
162 7
                            ->end()
163 7
                            ->scalarNode('stream_factory')
164 7
                                ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
165
                                ->defaultValue('httplug.stream_factory')
166 7
                                ->cannotBeEmpty()
167 7
                            ->end()
168 7
                            ->arrayNode('config')
169 7
                                ->addDefaultsIfNotSet()
170 7
                                ->children()
171 7
                                    ->scalarNode('default_ttl')->defaultNull()->end()
172 7
                                    ->scalarNode('respect_cache_headers')->defaultTrue()->end()
173 7
                                ->end()
174 7
                            ->end()
175 7
                        ->end()
176
                    ->end() // End cache plugin
177 7
178 7
                    ->arrayNode('cookie')
179 7
                    ->canBeEnabled()
180 7
                        ->children()
181 7
                            ->scalarNode('cookie_jar')
182 7
                                ->info('This must be a service id to a service implementing Http\Message\CookieJar')
183 7
                                ->isRequired()
184
                                ->cannotBeEmpty()
185 7
                            ->end()
186 7
                        ->end()
187 7
                    ->end() // End cookie plugin
188 7
189 7
                    ->arrayNode('decoder')
190 7
                    ->canBeDisabled()
191 7
                    ->addDefaultsIfNotSet()
192 7
                        ->children()
193 7
                            ->scalarNode('use_content_encoding')->defaultTrue()->end()
194 7
                        ->end()
195
                    ->end() // End decoder plugin
196 7
197 7
                    ->arrayNode('history')
198 7
                    ->canBeEnabled()
199 7
                        ->children()
200 7
                            ->scalarNode('journal')
201 7
                                ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
202 7
                                ->isRequired()
203 7
                                ->cannotBeEmpty()
204 7
                            ->end()
205 7
                        ->end()
206 7
                    ->end() // End history plugin
207 7
208 7
                    ->arrayNode('logger')
209 7
                    ->canBeDisabled()
210 7
                    ->addDefaultsIfNotSet()
211
                        ->children()
212 7
                            ->scalarNode('logger')
213 7
                                ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
214 7
                                ->defaultValue('logger')
215 7
                                ->cannotBeEmpty()
216 7
                            ->end()
217 7
                            ->scalarNode('formatter')
218 7
                                ->info('This must be a service id to a service implementing Http\Message\Formatter')
219 7
                                ->defaultNull()
220
                            ->end()
221 7
                        ->end()
222 7
                    ->end() // End logger plugin
223 7
224 7
                    ->arrayNode('redirect')
225 7
                    ->canBeDisabled()
226 7
                    ->addDefaultsIfNotSet()
227 7
                        ->children()
228
                            ->scalarNode('preserve_header')->defaultTrue()->end()
229 7
                            ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
230 7
                        ->end()
231 7
                    ->end() // End redirect plugin
232 7
233 7
                    ->arrayNode('retry')
234 7
                    ->canBeDisabled()
235 7
                    ->addDefaultsIfNotSet()
236 7
                        ->children()
237 7
                            ->scalarNode('retry')->defaultValue(1)->end()
238 7
                        ->end()
239 7
                    ->end() // End retry plugin
240
241 7
                    ->arrayNode('stopwatch')
242 7
                    ->canBeDisabled()
243 7
                    ->addDefaultsIfNotSet()
244 7
                        ->children()
245
                            ->scalarNode('stopwatch')
246
                                ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
247
                                ->defaultValue('debug.stopwatch')
248
                                ->cannotBeEmpty()
249
                            ->end()
250
                        ->end()
251 7
                    ->end() // End stopwatch plugin
252
253 7
                ->end()
254 7
            ->end()
255
        ->end();
256 7
    }
257 7
258 7
    /**
259 7
     * Add configuration for authentication plugin.
260 7
     *
261 2
     * @return ArrayNodeDefinition|\Symfony\Component\Config\Definition\Builder\NodeDefinition
262 2
     */
263 1
    private function addAuthenticationPluiginNode()
264 1
    {
265 2
        $builder = new TreeBuilder();
266 1
        $node = $builder->root('authentication');
267 1
        $node
268 2
            ->useAttributeAsKey('name')
269 2
            ->prototype('array')
270 1
                ->validate()
271 1
                    ->always()
272 1
                    ->then(function ($config) {
273 1
                        switch ($config['type']) {
274 1
                            case 'basic':
275
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
276 1
                                break;
277 7
                            case 'bearer':
278 7
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
279 7
                                break;
280 7
                            case 'service':
281 7
                                $this->validateAuthenticationType(['service'], $config, 'service');
282 7
                                break;
283 7
                            case 'wsse':
284 7
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
285 7
                                break;
286 7
                        }
287 7
288 7
                        return $config;
289 7
                    })
290 7
                ->end()
291 7
                ->children()
292
                    ->enumNode('type')
293 7
                        ->values(['basic', 'bearer', 'wsse', 'service'])
294
                        ->isRequired()
295
                        ->cannotBeEmpty()
296
                    ->end()
297
                    ->scalarNode('username')->end()
298
                    ->scalarNode('password')->end()
299
                    ->scalarNode('token')->end()
300
                    ->scalarNode('service')->end()
301
                    ->end()
302
                ->end()
303
            ->end(); // End authentication plugin
304
305 2
        return $node;
306
    }
307 2
308 2
    /**
309 2
     * Validate that the configuration fragment has the specified keys and none other.
310 2
     *
311
     * @param array  $expected Fields that must exist
312 2
     * @param array  $actual   Actual configuration hashmap
313 1
     * @param string $authName Name of authentication method for error messages
314
     *
315
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
316 1
     */
317 1
    private function validateAuthenticationType(array $expected, array $actual, $authName)
318 1
    {
319 1
        unset($actual['type']);
320 1
        $actual = array_keys($actual);
321 1
        sort($actual);
322
        sort($expected);
323
324
        if ($expected === $actual) {
325
            return;
326
        }
327
328
        throw new InvalidConfigurationException(sprintf(
329
            'Authentication "%s" requires %s but got %s',
330
            $authName,
331
            implode(', ', $expected),
332
            implode(', ', $actual)
333
        ));
334
    }
335
}
336