Completed
Pull Request — master (#30)
by Tobias
15:27 queued 08:41
created

AddHostPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 96%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
c 2
b 0
f 0
lcom 1
cbo 3
dl 0
loc 63
ccs 24
cts 25
cp 0.96
rs 10

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 5
    public function __construct(UriInterface $host, array $config = [])
35
    {
36 5
        if ($host->getHost() === '') {
37
            throw new \LogicException('Host can not be empty');
38
        }
39
40 5
        $this->host = $host;
41
42 5
        $resolver = new OptionsResolver();
43 5
        $this->configureOptions($resolver);
44 5
        $options = $resolver->resolve($config);
45
46 5
        $this->replace = $options['replace'];
47 5
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 3
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
53
    {
54 3
        if ($this->replace || $request->getUri()->getHost() === '') {
55 2
            $uri = $request->getUri()
56 2
                ->withHost($this->host->getHost())
57 2
                ->withScheme($this->host->getScheme())
58 2
                ->withPort($this->host->getPort())
59 2
            ;
60
61 2
            $request = $request->withUri($uri);
62 2
        }
63
64 3
        return $next($request);
65
    }
66
67
    /**
68
     * @param OptionsResolver $resolver
69
     */
70 5
    private function configureOptions(OptionsResolver $resolver)
71
    {
72 5
        $resolver->setDefaults([
73 5
            'replace' => false,
74 5
        ]);
75 5
        $resolver->setAllowedTypes('replace', 'bool');
76 5
    }
77
}
78