1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Http\Client\Common\Plugin; |
4
|
|
|
|
5
|
|
|
use Http\Client\Common\Plugin; |
6
|
|
|
use Psr\Http\Message\RequestInterface; |
7
|
|
|
use Psr\Http\Message\UriInterface; |
8
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Add schema and host to a request. Can be set to overwrite the schema and host if desired. |
12
|
|
|
* |
13
|
|
|
* @author Tobias Nyholm <[email protected]> |
14
|
|
|
* |
15
|
|
|
* TODO: make class final in version 2.0, once plugins does not extend it anymore. |
16
|
|
|
*/ |
17
|
|
|
/*final*/ class AddHostPlugin implements Plugin |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var UriInterface |
21
|
|
|
*/ |
22
|
|
|
private $host; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var bool |
26
|
|
|
*/ |
27
|
|
|
private $replace; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param UriInterface $host |
31
|
|
|
* @param array $config { |
32
|
|
|
* |
33
|
|
|
* @var bool $replace True will replace all hosts, false will only add host when none is specified. |
34
|
|
|
* } |
35
|
|
|
*/ |
36
|
5 |
|
public function __construct(UriInterface $host, array $config = []) |
37
|
|
|
{ |
38
|
5 |
|
if ($host->getHost() === '') { |
39
|
|
|
throw new \LogicException('Host can not be empty'); |
40
|
|
|
} |
41
|
|
|
|
42
|
5 |
|
$this->host = $host; |
43
|
|
|
|
44
|
5 |
|
$resolver = new OptionsResolver(); |
45
|
5 |
|
$this->configureOptions($resolver); |
46
|
5 |
|
$options = $resolver->resolve($config); |
47
|
|
|
|
48
|
5 |
|
$this->replace = $options['replace']; |
49
|
5 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
3 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
55
|
|
|
{ |
56
|
3 |
|
if ($this->replace || $request->getUri()->getHost() === '') { |
57
|
2 |
|
$uri = $request->getUri()->withHost($this->host->getHost()); |
58
|
2 |
|
$uri = $uri->withScheme($this->host->getScheme()); |
59
|
|
|
|
60
|
2 |
|
$request = $request->withUri($uri); |
61
|
2 |
|
} |
62
|
|
|
|
63
|
3 |
|
return $next($request); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param OptionsResolver $resolver |
68
|
|
|
*/ |
69
|
5 |
|
private function configureOptions(OptionsResolver $resolver) |
70
|
|
|
{ |
71
|
5 |
|
$resolver->setDefaults([ |
72
|
5 |
|
'replace' => false, |
73
|
5 |
|
]); |
74
|
5 |
|
$resolver->setAllowedTypes('replace', 'bool'); |
75
|
5 |
|
} |
76
|
|
|
} |
77
|
|
|
|