Completed
Push — master ( 96c43b...fcf598 )
by Tobias
03:54
created

AddHostPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 95.45%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 63
ccs 21
cts 22
cp 0.9545
rs 10
c 0
b 0
f 0

3 Methods

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