Completed
Pull Request — master (#83)
by Tobias
13:54 queued 08:51
created

Configuration::validateAuthenticationType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 9.4285
cc 2
eloc 12
nc 2
nop 3
crap 2
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 7
                    ->arrayNode('plugins')
114 7
                        ->info('A list of service ids of plugins. The order is important.')
115 7
                        ->prototype('scalar')->end()
116 7
                    ->end()
117 7
                    ->variableNode('config')->defaultValue([])->end()
118 7
                ->end()
119 7
            ->end();
120 7
    }
121
122
    /**
123
     * @param ArrayNodeDefinition $root
124
     */
125 7
    protected function configurePlugins(ArrayNodeDefinition $root)
126
    {
127 7
        $root->children()
128 7
            ->arrayNode('plugins')
129 7
                ->addDefaultsIfNotSet()
130 7
                ->children()
131 7
                    ->append($this->addAuthenticationPluiginNode())
132
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 7
                                ->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
157 7
                    ->arrayNode('cookie')
158 7
                    ->canBeEnabled()
159 7
                        ->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
176 7
                    ->arrayNode('history')
177 7
                    ->canBeEnabled()
178 7
                        ->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
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 7
                                ->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
203 7
                    ->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
220 7
                    ->arrayNode('stopwatch')
221 7
                    ->canBeDisabled()
222 7
                    ->addDefaultsIfNotSet()
223 7
                        ->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 7
                            ->end()
229 7
                        ->end()
230 7
                    ->end() // End stopwatch plugin
231
232 7
                ->end()
233 7
            ->end()
234 7
        ->end();
235 7
    }
236
237
    /**
238
     * Add configuration for authentication plugin.
239
     *
240
     * @return ArrayNodeDefinition|\Symfony\Component\Config\Definition\Builder\NodeDefinition
241
     */
242 7
    private function addAuthenticationPluiginNode()
243
    {
244 7
        $builder = new TreeBuilder();
245 7
        $node = $builder->root('authentication');
246
        $node
247 7
            ->useAttributeAsKey('name')
248 7
            ->prototype('array')
249 7
                ->validate()
250 7
                    ->always()
251 7
                    ->then(function ($config) {
252 2
                        switch ($config['type']) {
253 2
                            case 'basic':
254 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'basic');
255 1
                                break;
256 2
                            case 'bearer':
257 1
                                $this->validateAuthenticationType(['token'], $config, 'bearer');
258 1
                                break;
259 2
                            case 'service':
260 2
                                $this->validateAuthenticationType(['service'], $config, 'service');
261 1
                                break;
262 1
                            case 'wsse':
263 1
                                $this->validateAuthenticationType(['username', 'password'], $config, 'wsse');
264 1
                                break;
265 1
                        }
266
267 1
                        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 7
                    ->end()
276 7
                    ->scalarNode('username')->end()
277 7
                    ->scalarNode('password')->end()
278 7
                    ->scalarNode('token')->end()
279 7
                    ->scalarNode('service')->end()
280 7
                    ->end()
281 7
                ->end()
282 7
            ->end(); // End authentication plugin
283
284 7
        return $node;
285
    }
286
287
    /**
288
     * Validate that the configuration fragment has the specified keys and none other.
289
     *
290
     * @param array  $expected Fields that must exist
291
     * @param array  $actual   Actual configuration hashmap
292
     * @param string $authName Name of authentication method for error messages
293
     *
294
     * @throws InvalidConfigurationException If $actual does not have exactly the keys specified in $expected (plus 'type')
295
     */
296 2
    private function validateAuthenticationType(array $expected, array $actual, $authName)
297
    {
298 2
        unset($actual['type']);
299 2
        $actual = array_keys($actual);
300 2
        sort($actual);
301 2
        sort($expected);
302
303 2
        if ($expected === $actual) {
304 1
            return;
305
        }
306
307 1
        throw new InvalidConfigurationException(sprintf(
308 1
            'Authentication "%s" requires %s but got %s',
309 1
            $authName,
310 1
            implode(', ', $expected),
311 1
            implode(', ', $actual)
312 1
        ));
313
    }
314
}
315