Completed
Push — master ( 70eb5f...7033dc )
by Joel
02:46
created

AddHostPlugin::handleRequest()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 6
nc 2
nop 3
crap 3
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