Completed
Pull Request — master (#42)
by Tobias
12:28
created

BaseHostPlugin::handleRequest()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 6
nc 2
nop 3
crap 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
     * @param UriInterface $baseUri
28
     * @param array        $config {
29
     *     @var bool $replace True will replace all hosts, false will only add host when none is specified.
30
     * }
31
     */
32 5
    public function __construct(UriInterface $baseUri, array $config = [])
33
    {
34 5
        $this->baseUri = $baseUri;
35
36 5
        $resolver = new OptionsResolver();
37 5
        $this->configureOptions($resolver);
38 5
        $options = $resolver->resolve($config);
39
40 5
        $this->replace = $options['replace'];
41 5
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 3
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
47
    {
48 3
        if ($this->replace || $request->getUri()->getHost() === '') {
49 2
            $uri = $request->getUri()->withHost($this->baseUri->getHost());
50 2
            $uri = $uri->withScheme($this->baseUri->getScheme());
51
52 2
            $request = $request->withUri($uri);
53 2
        }
54
55 3
        return $next($request);
56
    }
57
58
    /**
59
     * @param OptionsResolver $resolver
60
     */
61 5
    private function configureOptions(OptionsResolver $resolver)
62
    {
63 5
        $resolver->setDefaults([
64 5
            'replace' => false,
65 5
        ]);
66 5
        $resolver->setAllowedTypes('replace', 'bool');
67 5
    }
68
}
69