Completed
Pull Request — master (#83)
by Tobias
09:31
created

Configuration::getConfigTreeBuilder()   B

Complexity

Conditions 7
Paths 1

Size

Total Lines 67
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 7

Importance

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