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
|
|
|
public function __construct(UriFactory $factory, $baseUri) |
26
|
|
|
{ |
27
|
|
|
$this->factory = $factory; |
28
|
|
|
$this->baseUri = $baseUri; |
29
|
|
|
} |
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
|
|
|
public function handleRequest(RequestInterface $request, callable $next, callable $first) |
41
|
|
|
{ |
42
|
|
|
$uri = $request->getUri(); |
43
|
|
|
$uriString = $uri->__toString(); |
44
|
|
|
if (!strpos($uriString, '://')) { |
45
|
|
|
if (substr($uriString, 0, 1) !== '/') { |
46
|
|
|
// Append baseUri this url |
47
|
|
|
$request = $request->withUri($this->factory->createUri($this->baseUri.$uriString)); |
48
|
|
|
} else { |
49
|
|
|
// Replace add/replace path and query to the baseUri |
50
|
|
|
$modifiedUri = $this->factory->createUri($this->baseUri); |
51
|
|
|
$modifiedUri = $modifiedUri->withPath($uri->getPath()); |
52
|
|
|
$modifiedUri = $modifiedUri->withQuery($uri->getQuery()); |
53
|
|
|
$request = $request->withUri($modifiedUri); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $next($request); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|