|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\Restful\Http; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\Restful\Application\Exceptions\BadRequestException; |
|
7
|
|
|
use kalanis\Restful\Exceptions\InvalidStateException; |
|
8
|
|
|
use kalanis\Restful\Mapping\Exceptions\MappingException; |
|
9
|
|
|
use kalanis\Restful\Mapping\MapperContext; |
|
10
|
|
|
use kalanis\Restful\Validation\IValidationScopeFactory; |
|
11
|
|
|
use Nette\Http\IRequest; |
|
12
|
|
|
|
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* InputFactory |
|
16
|
|
|
* @package kalanis\Restful\Http |
|
17
|
|
|
*/ |
|
18
|
|
|
class InputFactory |
|
19
|
|
|
{ |
|
20
|
|
|
|
|
21
|
1 |
|
public function __construct( |
|
22
|
|
|
protected readonly IRequest $httpRequest, |
|
23
|
|
|
private readonly MapperContext $mapperContext, |
|
24
|
|
|
private readonly IValidationScopeFactory $validationScopeFactory, |
|
25
|
|
|
) |
|
26
|
|
|
{ |
|
27
|
1 |
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Create input |
|
31
|
|
|
* @return Input<string, mixed> |
|
32
|
|
|
*/ |
|
33
|
|
|
public function create(): Input |
|
34
|
|
|
{ |
|
35
|
1 |
|
$input = new Input($this->validationScopeFactory); |
|
36
|
1 |
|
$input->setData($this->parseData()); |
|
37
|
1 |
|
return $input; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Parse data for input |
|
42
|
|
|
* |
|
43
|
|
|
* @throws BadRequestException |
|
44
|
|
|
* @return array<string, mixed> |
|
45
|
|
|
*/ |
|
46
|
|
|
protected function parseData(): array |
|
47
|
|
|
{ |
|
48
|
1 |
|
$postQuery = (array) $this->httpRequest->getPost(); |
|
49
|
1 |
|
$urlQuery = (array) $this->httpRequest->getQuery(); |
|
50
|
1 |
|
$requestBody = $this->parseRequestBody(); |
|
51
|
|
|
|
|
52
|
1 |
|
return array_merge($urlQuery, $postQuery, $requestBody); // $requestBody must be the last one!!! |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Parse request body if any |
|
57
|
|
|
* @throws BadRequestException |
|
58
|
|
|
* @return array<string, mixed> |
|
59
|
|
|
*/ |
|
60
|
|
|
protected function parseRequestBody(): array |
|
61
|
|
|
{ |
|
62
|
1 |
|
$requestBody = []; |
|
63
|
1 |
|
$input = $this->httpRequest->getRawBody(); |
|
64
|
|
|
|
|
65
|
1 |
|
if ($input) { |
|
66
|
|
|
try { |
|
67
|
|
|
$mapper = $this->mapperContext->getMapper($this->httpRequest->getHeader('Content-Type')); |
|
68
|
|
|
$requestBody = (array) $mapper->parse($input); |
|
69
|
|
|
} catch (InvalidStateException $e) { |
|
70
|
|
|
throw BadRequestException::unsupportedMediaType( |
|
71
|
|
|
'No mapper defined for Content-Type ' . $this->httpRequest->getHeader('Content-Type'), |
|
72
|
|
|
$e |
|
73
|
|
|
); |
|
74
|
|
|
} catch (MappingException $e) { |
|
75
|
|
|
throw new BadRequestException($e->getMessage(), 400, $e); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
1 |
|
return $requestBody; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|