Completed
Pull Request — master (#42)
by Tobias
10:07 queued 08:06
created

BaseUriPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4286
cc 1
eloc 3
nc 1
nop 2
crap 1
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
}
60