PluginProbe
DecaLog / 4.4.0
DecaLog v4.4.0
3.0.2 3.1.0 3.10.0 3.2.0 3.3.0 3.4.0 3.4.1 3.5.0 3.5.1 3.6.0 3.6.1 3.6.2 3.6.3 3.7.0 3.7.1 3.8.0 3.9.0 3.9.1 4.0.0 4.1.0 4.2.0 4.3.0 4.3.1 4.4.0 4.5.0 All 75 releases
decalog / includes / libraries / http / client-common / Plugin / AddHostPlugin.php

AddHostPlugin.php in DecaLog 4.4.0, at includes/libraries/http/client-common/Plugin/AddHostPlugin.php

77 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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