Completed
Pull Request — master (#42)
by Tobias
08:29
created

BaseUriPlugin::modifyUri()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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