/
HttplugExtension.php
518 lines (438 loc) · 18.9 KB
/
HttplugExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<?php
namespace Http\HttplugBundle\DependencyInjection;
use Http\Client\Common\BatchClient;
use Http\Client\Common\BatchClientInterface;
use Http\Client\Common\FlexibleHttpClient;
use Http\Client\Common\HttpMethodsClient;
use Http\Client\Common\HttpMethodsClientInterface;
use Http\Client\Common\Plugin\AuthenticationPlugin;
use Http\Client\Common\PluginClient;
use Http\Client\Common\PluginClientFactory;
use Http\Client\HttpAsyncClient;
use Http\Client\HttpClient;
use Http\Message\Authentication\BasicAuth;
use Http\Message\Authentication\Bearer;
use Http\Message\Authentication\QueryParam;
use Http\Message\Authentication\Wsse;
use Http\Mock\Client as MockClient;
use Psr\Http\Message\UriInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Twig\Environment as TwigEnvironment;
/**
* @author David Buchmann <mail@davidbu.ch>
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class HttplugExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$loader->load('plugins.xml');
if (\class_exists(MockClient::class)) {
$loader->load('mock-client.xml');
}
// Register default services
foreach ($config['classes'] as $service => $class) {
if (!empty($class)) {
$container->register(sprintf('httplug.%s.default', $service), $class);
}
}
// Set main aliases
foreach ($config['main_alias'] as $type => $id) {
$container->setAlias(sprintf('httplug.%s', $type), new Alias($id, true));
}
// Configure toolbar
$profilingEnabled = $this->isConfigEnabled($container, $config['profiling']);
if ($profilingEnabled) {
$loader->load('data-collector.xml');
if (!empty($config['profiling']['formatter'])) {
// Add custom formatter
$container
->getDefinition('httplug.collector.formatter')
->replaceArgument(0, new Reference($config['profiling']['formatter']))
;
}
$container
->getDefinition('httplug.formatter.full_http_message')
->addArgument($config['profiling']['captured_body_length'])
;
if (!class_exists(TwigEnvironment::class) && !class_exists(\Twig_Environment::class)) {
$container->removeDefinition('httplug.collector.twig.http_message');
}
}
$this->configureClients($container, $config);
$this->configurePlugins($container, $config['plugins']); // must be after clients, as clients.X.plugins might use plugins as templates that will be removed
$this->configureAutoDiscoveryClients($container, $config);
if (!$config['default_client_autowiring']) {
$container->removeAlias(HttpAsyncClient::class);
$container->removeAlias(HttpClient::class);
}
}
/**
* Configure client services.
*
* @param ContainerBuilder $container
* @param array $config
*/
private function configureClients(ContainerBuilder $container, array $config)
{
$first = null;
$clients = [];
foreach ($config['clients'] as $name => $arguments) {
if (null === $first) {
// Save the name of the first configured client.
$first = $name;
}
$this->configureClient($container, $name, $arguments);
$clients[] = $name;
}
// If we have clients configured
if (null !== $first) {
// If we do not have a client named 'default'
if (!array_key_exists('default', $config['clients'])) {
$serviceId = 'httplug.client.'.$first;
// Alias the first client to httplug.client.default
$container->setAlias('httplug.client.default', $serviceId);
$default = $first;
} else {
$default = 'default';
$serviceId = 'httplug.client.'.$default;
}
// Autowiring alias for special clients, if they are enabled on the default client
if ($config['clients'][$default]['flexible_client']) {
$container->setAlias(FlexibleHttpClient::class, $serviceId.'.flexible');
}
if ($config['clients'][$default]['http_methods_client']) {
if (\interface_exists(HttpMethodsClientInterface::class)) {
// support for client-common 1.9
$container->setAlias(HttpMethodsClientInterface::class, $serviceId.'.http_methods');
}
}
if ($config['clients'][$default]['batch_client']) {
if (\interface_exists(BatchClientInterface::class)) {
// support for client-common 1.9
$container->setAlias(BatchClientInterface::class, $serviceId.'.batch_client');
}
}
}
}
/**
* Configure all Httplug plugins or remove their service definition.
*
* @param ContainerBuilder $container
* @param array $config
*/
private function configurePlugins(ContainerBuilder $container, array $config)
{
if (!empty($config['authentication'])) {
$this->configureAuthentication($container, $config['authentication']);
}
unset($config['authentication']);
foreach ($config as $name => $pluginConfig) {
$pluginId = 'httplug.plugin.'.$name;
if ($this->isConfigEnabled($container, $pluginConfig)) {
$def = $container->getDefinition($pluginId);
$this->configurePluginByName($name, $def, $pluginConfig, $container, $pluginId);
}
}
}
/**
* @param string $name
* @param Definition $definition
* @param array $config
* @param ContainerBuilder $container In case we need to add additional services for this plugin
* @param string $serviceId service id of the plugin, in case we need to add additional services for this plugin
*/
private function configurePluginByName($name, Definition $definition, array $config, ContainerBuilder $container, $serviceId)
{
switch ($name) {
case 'cache':
$options = $config['config'];
if (!empty($options['cache_key_generator'])) {
$options['cache_key_generator'] = new Reference($options['cache_key_generator']);
}
$definition
->replaceArgument(0, new Reference($config['cache_pool']))
->replaceArgument(1, new Reference($config['stream_factory']))
->replaceArgument(2, $options);
break;
case 'cookie':
$definition->replaceArgument(0, new Reference($config['cookie_jar']));
break;
case 'decoder':
$definition->addArgument([
'use_content_encoding' => $config['use_content_encoding'],
]);
break;
case 'history':
$definition->replaceArgument(0, new Reference($config['journal']));
break;
case 'logger':
$definition->replaceArgument(0, new Reference($config['logger']));
if (!empty($config['formatter'])) {
$definition->replaceArgument(1, new Reference($config['formatter']));
}
break;
case 'redirect':
$definition->addArgument([
'preserve_header' => $config['preserve_header'],
'use_default_for_multiple' => $config['use_default_for_multiple'],
]);
break;
case 'retry':
$definition->addArgument([
'retries' => $config['retry'],
]);
break;
case 'stopwatch':
$definition->replaceArgument(0, new Reference($config['stopwatch']));
break;
/* client specific plugins */
case 'add_host':
$hostUriService = $serviceId.'.host_uri';
$this->createUri($container, $hostUriService, $config['host']);
$definition->replaceArgument(0, new Reference($hostUriService));
$definition->replaceArgument(1, [
'replace' => $config['replace'],
]);
break;
case 'add_path':
$pathUriService = $serviceId.'.path_uri';
$this->createUri($container, $pathUriService, $config['path']);
$definition->replaceArgument(0, new Reference($pathUriService));
break;
case 'base_uri':
$baseUriService = $serviceId.'.base_uri';
$this->createUri($container, $baseUriService, $config['uri']);
$definition->replaceArgument(0, new Reference($baseUriService));
$definition->replaceArgument(1, [
'replace' => $config['replace'],
]);
break;
case 'content_type':
$definition->replaceArgument(0, $config);
break;
case 'header_append':
case 'header_defaults':
case 'header_set':
case 'header_remove':
$definition->replaceArgument(0, $config['headers']);
break;
case 'query_defaults':
$definition->replaceArgument(0, $config['parameters']);
break;
default:
throw new \InvalidArgumentException(sprintf('Internal exception: Plugin %s is not handled', $name));
}
}
/**
* @param ContainerBuilder $container
* @param array $config
*
* @return array list of service ids for the authentication plugins
*/
private function configureAuthentication(ContainerBuilder $container, array $config, $servicePrefix = 'httplug.plugin.authentication')
{
$pluginServices = [];
foreach ($config as $name => $values) {
$authServiceKey = sprintf($servicePrefix.'.%s.auth', $name);
switch ($values['type']) {
case 'bearer':
$container->register($authServiceKey, Bearer::class)
->addArgument($values['token']);
break;
case 'basic':
$container->register($authServiceKey, BasicAuth::class)
->addArgument($values['username'])
->addArgument($values['password']);
break;
case 'wsse':
$container->register($authServiceKey, Wsse::class)
->addArgument($values['username'])
->addArgument($values['password']);
break;
case 'query_param':
$container->register($authServiceKey, QueryParam::class)
->addArgument($values['params']);
break;
case 'service':
$authServiceKey = $values['service'];
break;
default:
throw new \LogicException(sprintf('Unknown authentication type: "%s"', $values['type']));
}
$pluginServiceKey = $servicePrefix.'.'.$name;
$container->register($pluginServiceKey, AuthenticationPlugin::class)
->addArgument(new Reference($authServiceKey))
;
$pluginServices[] = $pluginServiceKey;
}
return $pluginServices;
}
/**
* @param ContainerBuilder $container
* @param string $clientName
* @param array $arguments
*/
private function configureClient(ContainerBuilder $container, $clientName, array $arguments)
{
$serviceId = 'httplug.client.'.$clientName;
$plugins = [];
foreach ($arguments['plugins'] as $plugin) {
$pluginName = key($plugin);
$pluginConfig = current($plugin);
if ('reference' === $pluginName) {
$plugins[] = $pluginConfig['id'];
} elseif ('authentication' === $pluginName) {
$plugins = array_merge($plugins, $this->configureAuthentication($container, $pluginConfig, $serviceId.'.authentication'));
} else {
$plugins[] = $this->configurePlugin($container, $serviceId, $pluginName, $pluginConfig);
}
}
if (empty($arguments['service'])) {
$container
->register($serviceId.'.client', HttpClient::class)
->setFactory([new Reference($arguments['factory']), 'createClient'])
->addArgument($arguments['config'])
->setPublic(false);
} else {
$container
->setAlias($serviceId.'.client', new Alias($arguments['service'], false));
}
$definition = $container
->register($serviceId, PluginClient::class)
->setFactory([new Reference(PluginClientFactory::class), 'createClient'])
->addArgument(new Reference($serviceId.'.client'))
->addArgument(
array_map(
function ($id) {
return new Reference($id);
},
$plugins
)
)
->addArgument([
'client_name' => $clientName,
])
;
if (is_bool($arguments['public'])) {
$definition->setPublic($arguments['public']);
}
/*
* Decorate the client with clients from client-common
*/
if ($arguments['flexible_client']) {
$container
->register($serviceId.'.flexible', FlexibleHttpClient::class)
->addArgument(new Reference($serviceId.'.flexible.inner'))
->setPublic($arguments['public'] ? true : false)
->setDecoratedService($serviceId)
;
}
if ($arguments['http_methods_client']) {
$container
->register($serviceId.'.http_methods', HttpMethodsClient::class)
->setArguments([new Reference($serviceId.'.http_methods.inner'), new Reference('httplug.message_factory')])
->setPublic($arguments['public'] ? true : false)
->setDecoratedService($serviceId)
;
}
if ($arguments['batch_client']) {
$container
->register($serviceId.'.batch_client', BatchClient::class)
->setArguments([new Reference($serviceId.'.batch_client.inner')])
->setPublic($arguments['public'] ? true : false)
->setDecoratedService($serviceId)
;
}
}
/**
* Create a URI object with the default URI factory.
*
* @param ContainerBuilder $container
* @param string $serviceId Name of the private service to create
* @param string $uri String representation of the URI
*/
private function createUri(ContainerBuilder $container, $serviceId, $uri)
{
$container
->register($serviceId, UriInterface::class)
->setPublic(false)
->setFactory([new Reference('httplug.uri_factory'), 'createUri'])
->addArgument($uri)
;
}
/**
* Make the user can select what client is used for auto discovery. If none is provided, a service will be created
* by finding a client using auto discovery.
*
* @param ContainerBuilder $container
* @param array $config
*/
private function configureAutoDiscoveryClients(ContainerBuilder $container, array $config)
{
$httpClient = $config['discovery']['client'];
if ('auto' !== $httpClient) {
$container->removeDefinition('httplug.auto_discovery.auto_discovered_client');
$container->removeDefinition('httplug.collector.auto_discovered_client');
if (!empty($httpClient)) {
$container->setAlias('httplug.auto_discovery.auto_discovered_client', $httpClient);
$container->getAlias('httplug.auto_discovery.auto_discovered_client')->setPublic(false);
}
}
$asyncHttpClient = $config['discovery']['async_client'];
if ('auto' !== $asyncHttpClient) {
$container->removeDefinition('httplug.auto_discovery.auto_discovered_async');
$container->removeDefinition('httplug.collector.auto_discovered_async');
if (!empty($asyncHttpClient)) {
$container->setAlias('httplug.auto_discovery.auto_discovered_async', $asyncHttpClient);
$container->getAlias('httplug.auto_discovery.auto_discovered_async')->setPublic(false);
}
}
if (null === $httpClient && null === $asyncHttpClient) {
$container->removeDefinition('httplug.strategy');
return;
}
}
/**
* {@inheritdoc}
*/
public function getConfiguration(array $config, ContainerBuilder $container)
{
return new Configuration($container->getParameter('kernel.debug'));
}
/**
* Configure a plugin using the parent definition from plugins.xml.
*
* @param ContainerBuilder $container
* @param string $serviceId
* @param string $pluginName
* @param array $pluginConfig
*
* @return string configured service id
*/
private function configurePlugin(ContainerBuilder $container, $serviceId, $pluginName, array $pluginConfig)
{
$pluginServiceId = $serviceId.'.plugin.'.$pluginName;
$definition = class_exists(ChildDefinition::class)
? new ChildDefinition('httplug.plugin.'.$pluginName)
: new DefinitionDecorator('httplug.plugin.'.$pluginName);
$this->configurePluginByName($pluginName, $definition, $pluginConfig, $container, $pluginServiceId);
$container->setDefinition($pluginServiceId, $definition);
return $pluginServiceId;
}
}