Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| Form | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |
100.00% |
1 / 1 |
| body | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Util; |
| 6 | |
| 7 | use Celema\Core\Request; |
| 8 | |
| 9 | class Form |
| 10 | { |
| 11 | /** |
| 12 | * The submitted body as an array. |
| 13 | * |
| 14 | * PHP only populates the parsed body for form-encoded POST requests, so |
| 15 | * PUT and DELETE handlers — and JSON posts — have to read the raw body |
| 16 | * themselves. Returns an empty array when there is nothing to parse. |
| 17 | * |
| 18 | * @return array<array-key, mixed> |
| 19 | */ |
| 20 | public static function body(Request $request): array |
| 21 | { |
| 22 | $data = $request->form() ?? []; |
| 23 | |
| 24 | if ($data !== []) { |
| 25 | return $data; |
| 26 | } |
| 27 | |
| 28 | $contentType = strtolower(trim(explode(';', $request->header('Content-Type'))[0])); |
| 29 | |
| 30 | if ($contentType === 'application/json') { |
| 31 | $decoded = $request->json(); |
| 32 | |
| 33 | return is_array($decoded) ? $decoded : []; |
| 34 | } |
| 35 | |
| 36 | if ($contentType === 'application/x-www-form-urlencoded') { |
| 37 | parse_str((string) $request->body(), $parsed); |
| 38 | |
| 39 | return $parsed; |
| 40 | } |
| 41 | |
| 42 | return []; |
| 43 | } |
| 44 | } |