Completed
Pull Request — master (#84)
by Tobias
07:00
created

Configuration::getConfigTreeBuilder()   C

Complexity

Conditions 7
Paths 1

Size

Total Lines 72
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 59
CRAP Score 7

Importance

Changes 5
Bugs 0 Features 2
Metric Value
c 5
b 0
f 2
dl 0
loc 72
rs 6.7427
ccs 59
cts 59
cp 1
cc 7
eloc 61
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
                        ->scalarNode('captured_body_length')
87 7
                            ->defaultValue(0)
88 7
                            ->canNotBeEmpty()
89
                            ->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).')
90 7
                        ->end()
91
                    ->end()
92
                ->end()
93 7
            ->end();
94
95 7
        return $treeBuilder;
96 7
    }
97 7
98 7
    protected function configureClients(ArrayNodeDefinition $root)
99 7
    {
100 7
        $root->children()
101 7
            ->arrayNode('clients')
102 7
                ->validate()
103 7
                    ->ifTrue(function ($clients) {
104 7
                        foreach ($clients as $name => $config) {
105 7
                            return $config['flexible_client'] && $config['http_methods_client'];
106 7
                        }
107 7
108 7
                        return false;
109 7
                    })
110 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()
111 7
                ->useAttributeAsKey('name')
112 7
                ->prototype('array')
113
                ->children()
114
                    ->scalarNode('factory')
115
                        ->isRequired()
116
                        ->cannotBeEmpty()
117 7
                        ->info('The service id of a factory to use when creating the adapter.')
118
                    ->end()
119 7
                    ->booleanNode('flexible_client')
120 7
                        ->defaultFalse()
121 7
                        ->info('Set to true to get the client wrapped in a FlexibleHttpClient which emulates async or sync behavior.')
122 7
                    ->end()
123 7
                    ->booleanNode('http_methods_client')
124
                        ->defaultFalse()
125 7
                        ->info('Set to true to get the client wrapped in a HttpMethodsClient which emulates provides functions for HTTP verbs.')
126 7
                    ->end()
127 7
                    ->arrayNode('plugins')
128 7
                        ->info('A list of service ids of plugins. The order is important.')
129 7
                        ->prototype('scalar')->end()
130 7
                    ->end()
131 7
                    ->variableNode('config')->defaultValue([])->end()
132 7
                ->end()
133 7
            ->end();
134 7
    }
135 7
136 7
    /**
137 7
     * @param ArrayNodeDefinition $root
138 7
     */
139 7
    protected function configurePlugins(ArrayNodeDefinition $root)
140 7
    {
141 7
        $root->children()
142 7
            ->arrayNode('plugins')
143 7
                ->addDefaultsIfNotSet()
144 7
                ->children()
145 7
                    ->append($this->addAuthenticationPluiginNode())
146 7
147 7
                    ->arrayNode('cache')
148
                    ->canBeEnabled()
149 7
                    ->addDefaultsIfNotSet()
150 7
                        ->children()
151 7
                            ->scalarNode('cache_pool')
152 7
                                ->info('This must be a service id to a service implementing Psr\Cache\CacheItemPoolInterface')
153 7
                                ->isRequired()
154 7
                                ->cannotBeEmpty()
155 7
                            ->end()
156 7
                            ->scalarNode('stream_factory')
157 7
                                ->info('This must be a service id to a service implementing Http\Message\StreamFactory')
158 7
                                ->defaultValue('httplug.stream_factory')
159
                                ->cannotBeEmpty()
160 7
                            ->end()
161 7
                            ->arrayNode('config')
162 7
                                ->addDefaultsIfNotSet()
163 7
                                ->children()
164 7
                                    ->scalarNode('default_ttl')->defaultNull()->end()
165 7
                                    ->scalarNode('respect_cache_headers')->defaultTrue()->end()
166 7
                                ->end()
167
                            ->end()
168 7
                        ->end()
169 7
                    ->end() // End cache plugin
170 7
171 7
                    ->arrayNode('cookie')
172 7
                    ->canBeEnabled()
173 7
                        ->children()
174 7
                            ->scalarNode('cookie_jar')
175 7
                                ->info('This must be a service id to a service implementing Http\Message\CookieJar')
176 7
                                ->isRequired()
177 7
                                ->cannotBeEmpty()
178
                            ->end()
179 7
                        ->end()
180 7
                    ->end() // End cookie plugin
181 7
182 7
                    ->arrayNode('decoder')
183 7
                    ->canBeDisabled()
184 7
                    ->addDefaultsIfNotSet()
185 7
                        ->children()
186 7
                            ->scalarNode('use_content_encoding')->defaultTrue()->end()
187 7
                        ->end()
188 7
                    ->end() // End decoder plugin
189 7
190 7
                    ->arrayNode('history')
191 7
                    ->canBeEnabled()
192 7
                        ->children()
193 7
                            ->scalarNode('journal')
194
                                ->info('This must be a service id to a service implementing Http\Client\Plugin\Journal')
195 7
                                ->isRequired()
196 7
                                ->cannotBeEmpty()
197 7
                            ->end()
198 7
                        ->end()
199 7
                    ->end() // End history plugin
200 7
201 7
                    ->arrayNode('logger')
202 7
                    ->canBeDisabled()
203
                    ->addDefaultsIfNotSet()
204 7
                        ->children()
205 7
                            ->scalarNode('logger')
206 7
                                ->info('This must be a service id to a service implementing Psr\Log\LoggerInterface')
207 7
                                ->defaultValue('logger')
208 7
                                ->cannotBeEmpty()
209 7
                            ->end()
210 7
                            ->scalarNode('formatter')
211
                                ->info('This must be a service id to a service implementing Http\Message\Formatter')
212 7
                                ->defaultNull()
213 7
                            ->end()
214 7
                        ->end()
215 7
                    ->end() // End logger plugin
216 7
217 7
                    ->arrayNode('redirect')
218 7
                    ->canBeDisabled()
219 7
                    ->addDefaultsIfNotSet()
220 7
                        ->children()
221 7
                            ->scalarNode('preserve_header')->defaultTrue()->end()
222 7
                            ->scalarNode('use_default_for_multiple')->defaultTrue()->end()
223
                        ->end()
224 7
                    ->end() // End redirect plugin
225 7
226 7
                    ->arrayNode('retry')
227 7
                    ->canBeDisabled()
228
                    ->addDefaultsIfNotSet()
229
                        ->children()
230
                            ->scalarNode('retry')->defaultValue(1)->end()
231
                        ->end()
232
                    ->end() // End retry plugin
233
234 7
                    ->arrayNode('stopwatch')
235
                    ->canBeDisabled()
236 7
                    ->addDefaultsIfNotSet()
237 7
                        ->children()
238
                            ->scalarNode('stopwatch')
239 7
                                ->info('This must be a service id to a service extending Symfony\Component\Stopwatch\Stopwatch')
240 7
                                ->defaultValue('debug.stopwatch')
241 7
                                ->cannotBeEmpty()
242 7
                            ->end()
243 7
                        ->end()
244 2
                    ->end() // End stopwatch plugin
245 2
246 1
                ->end()
247 1
            ->end()
248 2
        ->end();
249 1
    }
250 1
251 2
    /**
252 2
     * Add configuration for authentication plugin.
253 1
     *
254 1
     * @return ArrayNodeDefinition|\Symfony\Component\Config\Definition\Builder\NodeDefinition
255 1
     */
256 1
    private function addAuthenticationPluiginNode()
257 1
    {
258
        $builder = new TreeBuilder();
259 1
        $node = $builder->root('authentication');
260 7
        $node
261 7
            ->useAttributeAsKey('name')
262 7
            ->prototype('array')
263 7
                ->validate()
264 7
                    ->always()
265 7
                    ->then(function ($config) {
266 7
                        switch ($config['type']) {
267 7
                            case 'basic':
268 7
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
269 7
                                break;
270 7
                            case 'bearer':
271 7
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
272 7
                                break;
273 7
                            case 'service':
274 7
                                $this->validateAuthenticationType(['service'], $config, 'service');
275
                                break;
276 7
                            case 'wsse':
277
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
278
                                break;
279
                        }
280
281
                        return $config;
282
                    })
283
                ->end()
284
                ->children()
285
                    ->enumNode('type')
286
                        ->values(['basic', 'bearer', 'wsse', 'service'])
287
                        ->isRequired()
288 2
                        ->cannotBeEmpty()
289
                    ->end()
290 2
                    ->scalarNode('username')->end()
291 2
                    ->scalarNode('password')->end()
292 2
                    ->scalarNode('token')->end()
293 2
                    ->scalarNode('service')->end()
294
                    ->end()
295 2
                ->end()
296 1
            ->end(); // End authentication plugin
297
298
        return $node;
299 1
    }
300 1
301 1
    /**
302 1
     * Validate that the configuration fragment has the specified keys and none other.
303 1
     *
304 1
     * @param array  $expected Fields that must exist
305
     * @param array  $actual   Actual configuration hashmap
306
     * @param string $authName Name of authentication method for error messages
307
     *
308
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
309
     */
310
    private function validateAuthenticationType(array $expected, array $actual, $authName)
311
    {
312
        unset($actual['type']);
313
        $actual = array_keys($actual);
314
        sort($actual);
315
        sort($expected);
316
317
        if ($expected === $actual) {
318
            return;
319
        }
320
321
        throw new InvalidConfigurationException(sprintf(
322
            'Authentication "%s" requires %s but got %s',
323
            $authName,
324
            implode(', ', $expected),
325
            implode(', ', $actual)
326
        ));
327
    }
328
}
329