Completed
Pull Request — master (#42)
by Tobias
09:45 queued 26s
created

AddHostPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 95.45%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 2
A handleRequest() 0 11 3
A configureOptions() 0 7 1
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
 * Add schema and host to a request. Can be set to overwrite the schema and host if desired.
11
 *
12
 * @author Tobias Nyholm <[email protected]>
13
 */
14
class AddHostPlugin implements Plugin
15
{
16
    /**
17
     * @var UriInterface
18
     */
19
    private $host;
20
21
    /**
22
     * @var bool
23
     */
24
    private $replace;
25
26
    /**
27
     * @param UriInterface $host
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 $host, array $config = [])
33
    {
34 5
        if ($host->getHost() === '') {
35
            throw new \LogicException('Host can not be empty');
36
        }
37
38 5
        $this->host = $host;
39
40 5
        $resolver = new OptionsResolver();
41 5
        $this->configureOptions($resolver);
42 5
        $options = $resolver->resolve($config);
43
44 5
        $this->replace = $options['replace'];
45 5
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 3
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
51
    {
52 3
        if ($this->replace || $request->getUri()->getHost() === '') {
53 2
            $uri = $request->getUri()->withHost($this->host->getHost());
54 2
            $uri = $uri->withScheme($this->host->getScheme());
55
56 2
            $request = $request->withUri($uri);
57 2
        }
58
59 3
        return $next($request);
60
    }
61
62
    /**
63
     * @param OptionsResolver $resolver
64
     */
65 5
    private function configureOptions(OptionsResolver $resolver)
66
    {
67 5
        $resolver->setDefaults([
68 5
            'replace' => false,
69 5
        ]);
70 5
        $resolver->setAllowedTypes('replace', 'bool');
71 5
    }
72
}
73