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
|
|
|
$parts = explode('?', $uriString, 2); |
63
|
|
|
$modifiedUri = $this->baseUri->withPath($this->baseUri->getPath().$parts[0]); |
64
|
|
|
if (isset($parts[1])) { |
65
|
|
|
$modifiedUri = $modifiedUri->withQuery($parts[1]); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $modifiedUri; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|