Repository navigation
Expand file tree
/
Copy path01_receive_api_request.php
More file actions
53 lines (40 loc) · 1.58 KB
/
Copy path01_receive_api_request.php
File metadata and controls
53 lines (40 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
use tommyknocker\struct\exception\FieldNotFoundException;
use tommyknocker\struct\Field;
use tommyknocker\struct\Struct;
use tommyknocker\struct\validation\rules\EmailRule;
use tommyknocker\struct\validation\rules\LengthRule;
// An API boundary: accept only a declared, validated registration request.
final class RegisterRequest extends Struct
{
protected const STRICT = true;
#[Field(validationRules: [new EmailRule()])]
public readonly string $email;
#[Field(validationRules: [new LengthRule(8, 128)])]
public readonly string $password;
#[Field(required: false)]
public readonly ?string $phone;
#[Field(default: 'en')]
public readonly string $locale;
}
$request = RegisterRequest::fromJson('{
"email": "alice@example.com",
"password": "correct-horse-battery-staple"
}');
// Application code gets real typed values, including explicit defaults.
if ($request->phone !== null || $request->locale !== 'en') {
throw new RuntimeException('Optional/default field handling failed');
}
try {
RegisterRequest::fromJson('{"email":"alice@example.com"}');
throw new RuntimeException('Missing password should have been rejected');
} catch (FieldNotFoundException $error) {
if ($error->fieldName !== 'password') {
throw $error;
}
echo 'Missing field: ' . $error->fieldName . "\n";
}
// Do not export a password-bearing input DTO as a public response.
echo json_encode(['acceptedEmail' => $request->email, 'locale' => $request->locale], JSON_THROW_ON_ERROR) . "\n";