|
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
|
|
|
|