Completed
Pull Request — master (#48)
by Sullivan
07:44
created

AddPathPlugin   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 2
dl 0
loc 31
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handleRequest() 0 8 1
A __construct() 0 8 2
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
9
/**
10
 * Add base path to the request URI. Useful for base API URLs like http://domain.com/api.
11
 *
12
 * @author Sullivan Senechal <[email protected]>
13
 */
14
final class AddPathPlugin implements Plugin
15
{
16
    /**
17
     * @var UriInterface
18
     */
19
    private $host;
20
21
    /**
22
     * @param UriInterface $host
23
     */
24 10
    public function __construct(UriInterface $host)
25
    {
26 10
        if (rtrim($host->getPath(), '/') === '') {
27 1
            throw new \LogicException('Host path cannot be empty');
28
        }
29
30 9
        $this->host = $host;
31 9
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 5
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
37
    {
38 5
        $request = $request->withUri($request->getUri()
39 5
            ->withPath(str_replace('//', '/', $this->host->getPath().$request->getUri()->getPath()))
40 5
        );
41
42 5
        return $next($request);
43
    }
44
}
45