|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace FondBot\Http; |
|
6
|
|
|
|
|
7
|
|
|
use FondBot\Helpers\Arr; |
|
8
|
|
|
use Psr\Http\Message\MessageInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
|
|
11
|
|
|
class Request |
|
12
|
|
|
{ |
|
13
|
|
|
private $parameters; |
|
14
|
|
|
private $headers; |
|
15
|
|
|
|
|
16
|
3 |
|
public function __construct(array $parameters, array $headers) |
|
17
|
|
|
{ |
|
18
|
3 |
|
$this->parameters = $parameters; |
|
19
|
3 |
|
$this->headers = $headers; |
|
20
|
3 |
|
} |
|
21
|
|
|
|
|
22
|
2 |
|
public static function fromMessage(MessageInterface $message): Request |
|
23
|
|
|
{ |
|
24
|
2 |
|
if ($message->getHeaderLine('content-type') === 'application/json') { |
|
25
|
|
|
$parameters = (array) json_decode($message->getBody()->getContents(), true); |
|
26
|
2 |
|
} elseif ($message instanceof ServerRequestInterface) { |
|
27
|
1 |
|
$parameters = array_merge($message->getQueryParams(), (array) $message->getParsedBody()); |
|
28
|
|
|
} else { |
|
29
|
2 |
|
$parameters = (array) json_decode($message->getBody()->getContents(), true); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
2 |
|
return new static($parameters, $message->getHeaders()); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Get request parameters. |
|
37
|
|
|
* |
|
38
|
|
|
* @return array |
|
39
|
|
|
*/ |
|
40
|
1 |
|
public function getParameters(): array |
|
41
|
|
|
{ |
|
42
|
1 |
|
return $this->parameters; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Get single parameter. |
|
47
|
|
|
* |
|
48
|
|
|
* @param string $key |
|
49
|
|
|
* @param mixed $default |
|
50
|
|
|
* |
|
51
|
|
|
* @return mixed |
|
52
|
|
|
*/ |
|
53
|
1 |
|
public function getParameter(string $key, $default = null) |
|
54
|
|
|
{ |
|
55
|
1 |
|
return Arr::get($this->parameters, $key, $default); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Determine if request has one or more parameters. |
|
60
|
|
|
* |
|
61
|
|
|
* @param array|string $keys |
|
62
|
|
|
* |
|
63
|
|
|
* @return bool |
|
64
|
|
|
*/ |
|
65
|
1 |
|
public function hasParameters($keys): bool |
|
66
|
|
|
{ |
|
67
|
1 |
|
return Arr::has($this->parameters, (array) $keys); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Get request headers. |
|
72
|
|
|
* |
|
73
|
|
|
* @return array |
|
74
|
|
|
*/ |
|
75
|
1 |
|
public function getHeaders(): array |
|
76
|
|
|
{ |
|
77
|
1 |
|
return $this->headers; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Get single request header. |
|
82
|
|
|
* |
|
83
|
|
|
* @param string $key |
|
84
|
|
|
* @param mixed $default |
|
85
|
|
|
* |
|
86
|
|
|
* @return mixed |
|
87
|
|
|
*/ |
|
88
|
1 |
|
public function getHeader(string $key, $default = null) |
|
89
|
|
|
{ |
|
90
|
1 |
|
return Arr::get($this->headers, $key, $default); |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|