1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Domain\User\Data; |
4
|
|
|
|
5
|
|
|
class UserData implements \JsonSerializable |
6
|
|
|
{ |
7
|
|
|
// Variable names matching database columns (camelCase instead of snake_case) |
8
|
|
|
public ?int $id; |
9
|
|
|
public ?string $firstName; |
10
|
|
|
public ?string $lastName; |
11
|
|
|
public ?string $email; |
12
|
|
|
public ?\DateTimeImmutable $updatedAt; |
13
|
|
|
public ?\DateTimeImmutable $createdAt; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param array<string, mixed> $userData |
17
|
|
|
*/ |
18
|
4 |
|
public function __construct(array $userData = []) |
19
|
|
|
{ |
20
|
|
|
// Keys may be taken from view form or database, so they have to correspond to both; otherwise use mapper |
21
|
4 |
|
$this->id = $userData['id'] ?? null; |
22
|
4 |
|
$this->firstName = $userData['first_name'] ?? null; |
23
|
4 |
|
$this->lastName = $userData['last_name'] ?? null; |
24
|
4 |
|
$this->email = $userData['email'] ?? null; |
25
|
|
|
try { |
26
|
4 |
|
$this->updatedAt = $userData['updated_at'] ?? null ? new \DateTimeImmutable($userData['updated_at']) : null; |
27
|
|
|
} catch (\Exception $e) { |
28
|
|
|
$this->updatedAt = null; |
29
|
|
|
} |
30
|
|
|
try { |
31
|
4 |
|
$this->createdAt = $userData['created_at'] ?? null ? new \DateTimeImmutable($userData['created_at']) : null; |
32
|
|
|
} catch (\Exception $e) { |
33
|
|
|
$this->createdAt = null; |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Convert the object to an array where the keys |
39
|
|
|
* represent the database fields. |
40
|
|
|
* |
41
|
|
|
* @return array<string, int|string|null> |
42
|
|
|
*/ |
43
|
2 |
|
public function toArrayForDatabase(): array |
44
|
|
|
{ |
45
|
2 |
|
return [ |
46
|
2 |
|
'id' => $this->id, |
47
|
2 |
|
'first_name' => $this->firstName, |
48
|
2 |
|
'last_name' => $this->lastName, |
49
|
2 |
|
'email' => $this->email, |
50
|
2 |
|
]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Define how json_encode() should serialize the object |
55
|
|
|
* camelCase according to Google recommendation https://stackoverflow.com/a/19287394/9013718. |
56
|
|
|
* |
57
|
|
|
* @return array<string, mixed> format expected by the frontend |
58
|
|
|
*/ |
59
|
2 |
|
public function jsonSerialize(): array |
60
|
|
|
{ |
61
|
|
|
// camelCase according to Google recommendation https://stackoverflow.com/a/19287394/9013718 |
62
|
2 |
|
return [ |
63
|
2 |
|
'id' => $this->id, |
64
|
2 |
|
'firstName' => $this->firstName, |
65
|
2 |
|
'lastName' => $this->lastName, |
66
|
2 |
|
'email' => $this->email, |
67
|
2 |
|
'updatedAt' => $this->updatedAt?->format('Y-m-d H:i:s'), |
68
|
2 |
|
'createdAt' => $this->createdAt?->format('Y-m-d H:i:s'), |
69
|
2 |
|
]; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|