Completed
Pull Request — master (#42)
by Tobias
27:36 queued 17:10
created

BaseUriPlugin::handleRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 2
eloc 5
nc 2
nop 3
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
    public function __construct(UriInterface $baseUri)
20
    {
21
        $this->baseUri = $baseUri;
22
    }
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
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
34
    {
35
        $uriString = $request->getUri()->__toString();
36
        if (!strpos($uriString, '://')) {
37
            $request = $request->withUri($this->modifyUri($request->getUri()));
38
        }
39
40
        return $next($request);
41
    }
42
43
    /**
44
     * @param UriInterface $uri
45
     *
46
     * @return UriInterface
47
     */
48
    private function modifyUri(UriInterface $uri)
49
    {
50
        $uriString = $uri->__toString();
51
        if (substr($uriString, 0, 1) === '/') {
52
            // Replace/Add path and query to the baseUri
53
            $modifiedUri = $this->baseUri->withPath($uri->getPath());
54
            $modifiedUri = $modifiedUri->withQuery($uri->getQuery());
55
        } else {
56
            // Append baseUri this url
57
            if ('' !== $query = $this->baseUri->getQuery()) {
58
                // Append the uri on the query
59
                $modifiedUri = $this->baseUri->withQuery($query.$uriString);
60
            } else {
61
                // Append the uri on path and query
62
                list($path, $query) = explode('?', $uriString, 2);
63
                $modifiedUri = $this->baseUri->withPath($this->baseUri->getPath().$path);
64
                $modifiedUri = $modifiedUri->withQuery($query);
65
            }
66
        }
67
68
        return $modifiedUri;
69
    }
70
}
71