| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Http\Client\Common\Plugin; |
| 6 |
|
| 7 |
use Http\Client\Common\Plugin; |
| 8 |
use Http\Promise\Promise; |
| 9 |
use Psr\Http\Message\RequestInterface; |
| 10 |
use Psr\Http\Message\UriInterface; |
| 11 |
use Symfony\Component\OptionsResolver\OptionsResolver; |
| 12 |
|
| 13 |
/** |
| 14 |
* Add schema, host and port to a request. Can be set to overwrite the schema and host if desired. |
| 15 |
* |
| 16 |
* @author Tobias Nyholm <tobias.nyholm@gmail.com> |
| 17 |
*/ |
| 18 |
final 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 array{'replace'?: bool} $config |
| 32 |
* |
| 33 |
* Configuration options: |
| 34 |
* - replace: True will replace all hosts, false will only add host when none is specified |
| 35 |
*/ |
| 36 |
public function __construct(UriInterface $host, array $config = []) |
| 37 |
{ |
| 38 |
if ('' === $host->getHost()) { |
| 39 |
throw new \LogicException('Host can not be empty'); |
| 40 |
} |
| 41 |
|
| 42 |
$this->host = $host; |
| 43 |
|
| 44 |
$resolver = new OptionsResolver(); |
| 45 |
$this->configureOptions($resolver); |
| 46 |
$options = $resolver->resolve($config); |
| 47 |
|
| 48 |
$this->replace = $options['replace']; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* {@inheritdoc} |
| 53 |
*/ |
| 54 |
public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise |
| 55 |
{ |
| 56 |
if ($this->replace || '' === $request->getUri()->getHost()) { |
| 57 |
$uri = $request->getUri() |
| 58 |
->withHost($this->host->getHost()) |
| 59 |
->withScheme($this->host->getScheme()) |
| 60 |
->withPort($this->host->getPort()) |
| 61 |
; |
| 62 |
|
| 63 |
$request = $request->withUri($uri); |
| 64 |
} |
| 65 |
|
| 66 |
return $next($request); |
| 67 |
} |
| 68 |
|
| 69 |
private function configureOptions(OptionsResolver $resolver): void |
| 70 |
{ |
| 71 |
$resolver->setDefaults([ |
| 72 |
'replace' => false, |
| 73 |
]); |
| 74 |
$resolver->setAllowedTypes('replace', 'bool'); |
| 75 |
} |
| 76 |
} |
| 77 |
|