Completed
Push — master ( 3e25b9...556647 )
by Márk
11s
created

AddHostPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 95.45%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 60
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\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 and host 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()->withHost($this->host->getHost());
56 2
            $uri = $uri->withScheme($this->host->getScheme());
57
58 2
            $request = $request->withUri($uri);
59 2
        }
60
61 3
        return $next($request);
62
    }
63
64
    /**
65
     * @param OptionsResolver $resolver
66
     */
67 5
    private function configureOptions(OptionsResolver $resolver)
68
    {
69 5
        $resolver->setDefaults([
70 5
            'replace' => false,
71 5
        ]);
72 5
        $resolver->setAllowedTypes('replace', 'bool');
73 5
    }
74
}
75