|
1
|
|
|
<?php |
|
2
|
|
|
namespace Wandu\Http\Factory; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\StreamInterface; |
|
5
|
|
|
use Wandu\Http\Factory\Exception\CannotCreateRequestException; |
|
6
|
|
|
use Wandu\Http\Psr\Request; |
|
7
|
|
|
use Wandu\Http\Psr\Stream; |
|
8
|
|
|
|
|
9
|
|
|
class RequestFactory |
|
10
|
|
|
{ |
|
11
|
|
|
use HelperTrait; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @param array $serverParams |
|
15
|
|
|
* @return \Psr\Http\Message\RequestInterface |
|
16
|
|
|
*/ |
|
17
|
|
|
public function createFromGlobals(array $serverParams = null) |
|
|
|
|
|
|
18
|
|
|
{ |
|
19
|
|
|
if (!isset($serverParams)) { |
|
20
|
|
|
$serverParams = $_SERVER; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
$method = isset($serverParams['REQUEST_METHOD']) ? $serverParams['REQUEST_METHOD'] : 'GET'; |
|
24
|
|
|
$uri = isset($serverParams['REQUEST_URI']) ? $serverParams['REQUEST_URI'] : '/'; |
|
25
|
|
|
|
|
26
|
|
|
$headers = $this->getPsrHeadersFromServerParams($serverParams); |
|
27
|
|
|
return new Request( |
|
28
|
|
|
$method, |
|
29
|
|
|
$this->makeUriObjectWithPsrHeaders($uri, $headers), |
|
30
|
|
|
isset($stream) ? $stream : new Stream('php://memory'), |
|
|
|
|
|
|
31
|
|
|
$headers, |
|
32
|
|
|
'1.1' |
|
33
|
|
|
); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param array $plainHeaders |
|
38
|
|
|
* @param \Psr\Http\Message\StreamInterface|null $stream |
|
39
|
|
|
* @return \Psr\Http\Message\RequestInterface |
|
40
|
|
|
* @throws \Wandu\Http\Factory\Exception\CannotCreateRequestException |
|
41
|
|
|
*/ |
|
42
|
2 |
|
public function createRequest(array $plainHeaders, StreamInterface $stream = null) |
|
43
|
|
|
{ |
|
44
|
2 |
|
if (count($plainHeaders) === 0) { |
|
45
|
|
|
throw new CannotCreateRequestException( |
|
46
|
|
|
'first parameter is array, and it must have at least one value.', |
|
47
|
|
|
100 |
|
48
|
|
|
); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
$httpInformation = explode(' ', array_shift($plainHeaders)); |
|
52
|
2 |
|
if (count($httpInformation) !== 3) { |
|
53
|
|
|
throw new CannotCreateRequestException('wrong http header.', 101); |
|
54
|
|
|
} |
|
55
|
2 |
|
list ($method, $uri, $serverProtocol) = $httpInformation; |
|
56
|
|
|
|
|
57
|
2 |
|
$headers = $this->getPsrHeadersFromPlainHeader($plainHeaders); |
|
58
|
2 |
|
return new Request( |
|
59
|
2 |
|
$method, |
|
60
|
2 |
|
$this->makeUriObjectWithPsrHeaders($uri, $headers), |
|
61
|
2 |
|
isset($stream) ? $stream : new Stream('php://memory'), |
|
62
|
2 |
|
$headers, |
|
63
|
2 |
|
explode('/', $serverProtocol)[1] |
|
64
|
|
|
); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: