Completed
Pull Request — master (#42)
by Tobias
15:04 queued 04:43
created

BaseHostPlugin::handleRequest()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
rs 9.4285
cc 3
eloc 6
nc 2
nop 3
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\UriInterface;
7
use Symfony\Component\OptionsResolver\OptionsResolver;
8
9
/**
10
 * Allow to modify the the schema and the host of an existing request.
11
 *
12
 * @author Tobias Nyholm <[email protected]>
13
 */
14
class BaseHostPlugin implements Plugin
15
{
16
    /**
17
     * @var UriInterface
18
     */
19
    private $baseUri;
20
21
    /**
22
     * @var bool
23
     */
24
    private $replace;
25
26
    /**
27
     * Available options for $config are:
28
     *  - replace: bool True will replace all hosts, false will only add host when none is specified.
29
     *
30
     * @param UriInterface $baseUri
31
     * @param array        $config
32
     */
33
    public function __construct(UriInterface $baseUri, array $config = [])
34
    {
35
        $this->baseUri = $baseUri;
36
37
        $resolver = new OptionsResolver();
38
        $this->configureOptions($resolver);
39
        $options = $resolver->resolve($config);
40
41
        $this->replace = $options['replace'];
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
48
    {
49
        if ($this->replace || $request->getUri()->getHost() === '') {
50
            $uri = $request->getUri()->withHost($this->baseUri->getHost());
51
            $uri = $uri->withScheme($this->baseUri->getScheme());
52
53
            $request = $request->withUri($uri);
54
        }
55
56
        return $next($request);
57
    }
58
59
    /**
60
     * @param OptionsResolver $resolver
61
     */
62
    private function configureOptions(OptionsResolver $resolver)
63
    {
64
        $resolver->setDefaults([
65
            'replace' => false,
66
        ]);
67
        $resolver->setAllowedTypes('replace', 'bool');
68
    }
69
}
70