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