|
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
|
|
|
final class AddHostPlugin implements Plugin |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var UriInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
private $host; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var bool |
|
24
|
|
|
*/ |
|
25
|
|
|
private $replace; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param UriInterface $host |
|
29
|
|
|
* @param array $config { |
|
30
|
|
|
* |
|
31
|
|
|
* @var bool $replace True will replace all hosts, false will only add host when none is specified. |
|
32
|
|
|
* } |
|
33
|
|
|
*/ |
|
34
|
5 |
|
public function __construct(UriInterface $host, array $config = []) |
|
35
|
|
|
{ |
|
36
|
5 |
|
if ($host->getHost() === '') { |
|
37
|
|
|
throw new \LogicException('Host can not be empty'); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
5 |
|
$this->host = $host; |
|
41
|
|
|
|
|
42
|
5 |
|
$resolver = new OptionsResolver(); |
|
43
|
5 |
|
$this->configureOptions($resolver); |
|
44
|
5 |
|
$options = $resolver->resolve($config); |
|
45
|
|
|
|
|
46
|
5 |
|
$this->replace = $options['replace']; |
|
47
|
5 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* {@inheritdoc} |
|
51
|
|
|
*/ |
|
52
|
3 |
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
|
53
|
|
|
{ |
|
54
|
3 |
|
if ($this->replace || $request->getUri()->getHost() === '') { |
|
55
|
2 |
|
$uri = $request->getUri()->withHost($this->host->getHost()); |
|
56
|
2 |
|
$uri = $uri->withScheme($this->host->getScheme()); |
|
57
|
|
|
|
|
58
|
2 |
|
$request = $request->withUri($uri); |
|
59
|
2 |
|
} |
|
60
|
|
|
|
|
61
|
3 |
|
return $next($request); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param OptionsResolver $resolver |
|
66
|
|
|
*/ |
|
67
|
5 |
|
private function configureOptions(OptionsResolver $resolver) |
|
68
|
|
|
{ |
|
69
|
5 |
|
$resolver->setDefaults([ |
|
70
|
5 |
|
'replace' => false, |
|
71
|
5 |
|
]); |
|
72
|
5 |
|
$resolver->setAllowedTypes('replace', 'bool'); |
|
73
|
5 |
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|