|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* It's free open-source software released under the MIT License. |
|
5
|
|
|
* |
|
6
|
|
|
* @author Anatoly Fenric <[email protected]> |
|
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Fenric |
|
8
|
|
|
* @license https://github.com/sunrise-php/http-message/blob/master/LICENSE |
|
9
|
|
|
* @link https://github.com/sunrise-php/http-message |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Message; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Import classes |
|
16
|
|
|
*/ |
|
17
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
|
18
|
|
|
use Psr\Http\Message\RequestInterface; |
|
19
|
|
|
use Psr\Http\Message\UriInterface; |
|
20
|
|
|
use InvalidArgumentException; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Import functions |
|
24
|
|
|
*/ |
|
25
|
|
|
use function json_encode; |
|
26
|
|
|
use function json_last_error; |
|
27
|
|
|
use function json_last_error_msg; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Import constants |
|
31
|
|
|
*/ |
|
32
|
|
|
use const JSON_ERROR_NONE; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* HTTP Request Message Factory |
|
36
|
|
|
* |
|
37
|
|
|
* @link https://www.php-fig.org/psr/psr-17/ |
|
38
|
|
|
*/ |
|
39
|
|
|
class RequestFactory implements RequestFactoryInterface |
|
40
|
|
|
{ |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* {@inheritdoc} |
|
44
|
|
|
*/ |
|
45
|
2 |
|
public function createRequest(string $method, $uri) : RequestInterface |
|
46
|
|
|
{ |
|
47
|
2 |
|
return new Request($method, $uri); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Creates JSON request |
|
52
|
|
|
* |
|
53
|
|
|
* @param string $method |
|
54
|
|
|
* @param string|UriInterface|null $uri |
|
55
|
|
|
* @param mixed $data |
|
56
|
|
|
* @param int $options |
|
57
|
|
|
* @param int $depth |
|
58
|
|
|
* |
|
59
|
|
|
* @return RequestInterface |
|
60
|
|
|
* |
|
61
|
|
|
* @throws InvalidArgumentException |
|
62
|
|
|
* If the data cannot be encoded. |
|
63
|
|
|
*/ |
|
64
|
2 |
|
public function createJsonRequest( |
|
65
|
|
|
string $method, |
|
66
|
|
|
$uri, |
|
67
|
|
|
$data, |
|
68
|
|
|
int $options = 0, |
|
69
|
|
|
int $depth = 512 |
|
70
|
|
|
) : RequestInterface { |
|
71
|
2 |
|
json_encode(''); // reset previous error... |
|
72
|
2 |
|
$content = json_encode($data, $options, $depth); |
|
73
|
2 |
|
if (JSON_ERROR_NONE <> json_last_error()) { |
|
74
|
1 |
|
throw new InvalidArgumentException(json_last_error_msg()); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
1 |
|
$request = new Request($method, $uri, [ |
|
78
|
1 |
|
'Content-Type' => 'application/json; charset=UTF-8', |
|
79
|
|
|
]); |
|
80
|
|
|
|
|
81
|
1 |
|
$request->getBody()->write($content); |
|
82
|
|
|
|
|
83
|
1 |
|
return $request; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|