Completed
Push — master ( 70eb5f...7033dc )
by Joel
02:46
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 1
Metric Value
wmc 6
c 1
b 0
f 1
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\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
     *
30
     *     @var bool $replace True will replace all hosts, false will only add host when none is specified.
31
     * }
32
     */
33 5
    public function __construct(UriInterface $host, array $config = [])
34
    {
35 5
        if ($host->getHost() === '') {
36
            throw new \LogicException('Host can not be empty');
37
        }
38
39 5
        $this->host = $host;
40
41 5
        $resolver = new OptionsResolver();
42 5
        $this->configureOptions($resolver);
43 5
        $options = $resolver->resolve($config);
44
45 5
        $this->replace = $options['replace'];
46 5
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 3
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
52
    {
53 3
        if ($this->replace || $request->getUri()->getHost() === '') {
54 2
            $uri = $request->getUri()->withHost($this->host->getHost());
55 2
            $uri = $uri->withScheme($this->host->getScheme());
56
57 2
            $request = $request->withUri($uri);
58 2
        }
59
60 3
        return $next($request);
61
    }
62
63
    /**
64
     * @param OptionsResolver $resolver
65
     */
66 5
    private function configureOptions(OptionsResolver $resolver)
67
    {
68 5
        $resolver->setDefaults([
69 5
            'replace' => false,
70 5
        ]);
71 5
        $resolver->setAllowedTypes('replace', 'bool');
72 5
    }
73
}
74