Completed
Pull Request — master (#83)
by Tobias
10:39
created

Configuration::addAuthenticationPluiginNode()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 44
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 5

Importance

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