Completed
Pull Request — master (#42)
by Tobias
02:32
created

BaseUriPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
c 1
b 0
f 1
lcom 1
cbo 3
dl 0
loc 51
ccs 17
cts 17
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handleRequest() 0 19 3
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Message\UriFactory;
6
use Http\Promise\Promise;
7
use Psr\Http\Message\RequestInterface;
8
9
class BaseUriPlugin implements Plugin
10
{
11
    /**
12
     * @var string
13
     */
14
    private $baseUri;
15
16
    /**
17
     * @var UriFactory
18
     */
19
    private $factory;
20
21
    /**
22
     * @param UriFactory $factory
23
     * @param string $baseUri
24
     */
25 5
    public function __construct(UriFactory $factory, $baseUri)
26
    {
27 5
        $this->factory = $factory;
28 5
        $this->baseUri = $baseUri;
29 5
    }
30
31
    /**
32
     * Handle the request and return the response coming from the next callable.
33
     *
34
     * @param RequestInterface $request
35
     * @param callable $next Next middleware in the chain, the request is passed as the first argument
36
     * @param callable $first First middleware in the chain, used to to restart a request
37
     *
38
     * @return Promise
39
     */
40 3
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
41
    {
42 3
        $uri = $request->getUri();
43 3
        $uriString = $uri->__toString();
44 3
        if (!strpos($uriString, '://')) {
45 2
            if (substr($uriString, 0, 1) !== '/') {
46
                // Append baseUri this url
47 1
                $request = $request->withUri($this->factory->createUri($this->baseUri.$uriString));
48 1
            } else {
49
                // Replace add/replace path and query to the baseUri
50 1
                $modifiedUri = $this->factory->createUri($this->baseUri);
51 1
                $modifiedUri = $modifiedUri->withPath($uri->getPath());
52 2
                $modifiedUri = $modifiedUri->withQuery($uri->getQuery());
53 1
                $request = $request->withUri($modifiedUri);
54
            }
55 2
        }
56
57 3
        return $next($request);
58
    }
59
}