Completed
Pull Request — master (#42)
by Tobias
20:16 queued 13:52
created

BaseUriPlugin::modifyUri()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0379

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
ccs 13
cts 15
cp 0.8667
rs 8.6846
cc 4
eloc 14
nc 4
nop 1
crap 4.0379
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Promise\Promise;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\UriInterface;
8
9
class BaseUriPlugin implements Plugin
10
{
11
    /**
12
     * @var UriInterface
13
     */
14
    private $baseUri;
15
16
    /**
17
     * @param UriInterface $baseUri
18
     */
19 6
    public function __construct(UriInterface $baseUri)
20
    {
21 6
        $this->baseUri = $baseUri;
22 6
    }
23
24
    /**
25
     * Handle the request and return the response coming from the next callable.
26
     *
27
     * @param RequestInterface $request
28
     * @param callable         $next    Next middleware in the chain, the request is passed as the first argument
29
     * @param callable         $first   First middleware in the chain, used to to restart a request
30
     *
31
     * @return Promise
32
     */
33 4
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
34
    {
35 4
        $uriString = $request->getUri()->__toString();
36 4
        if (!strpos($uriString, '://')) {
37 3
            $request = $request->withUri($this->modifyUri($request->getUri()));
38 3
        }
39
40 4
        return $next($request);
41
    }
42
43
    /**
44
     * @param UriInterface $uri
45
     *
46
     * @return UriInterface
47
     */
48 3
    private function modifyUri(UriInterface $uri)
49
    {
50 3
        $uriString = $uri->__toString();
51 3
        if (substr($uriString, 0, 1) === '/') {
52
            // Replace/Add path and query to the baseUri
53 1
            $modifiedUri = $this->baseUri->withPath($uri->getPath());
54 1
            $modifiedUri = $modifiedUri->withQuery($uri->getQuery());
55 1
        } else {
56
            // Append baseUri this url
57 2
            if ('' !== $query = $this->baseUri->getQuery()) {
58
                // Append the uri on the query
59 1
                $modifiedUri = $this->baseUri->withQuery($query.$uriString);
60 1
            } else {
61
                // Append the uri on path and query
62 1
                $parts = explode('?', $uriString, 2);
63 1
                $modifiedUri = $this->baseUri->withPath($this->baseUri->getPath().$parts[0]);
64 1
                if (isset($parts[1])) {
65
                    $modifiedUri = $modifiedUri->withQuery($parts[1]);
66
                }
67
            }
68
        }
69
70 3
        return $modifiedUri;
71
    }
72
}
73