Completed
Pull Request — master (#14)
by Márk
06:15
created

AddHostPlugin   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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