|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace midorikocak\nanoauth; |
|
6
|
|
|
|
|
7
|
|
|
use Exception; |
|
8
|
|
|
use midorikocak\nanodb\DatabaseInterface; |
|
9
|
|
|
use midorikocak\nanodb\RepositoryInterface; |
|
10
|
|
|
use midorikocak\querymaker\QueryInterface; |
|
11
|
|
|
use ReflectionException; |
|
12
|
|
|
|
|
13
|
|
|
use function array_map; |
|
14
|
|
|
|
|
15
|
|
|
class UserRepository implements RepositoryInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private DatabaseInterface $db; |
|
18
|
|
|
|
|
19
|
6 |
|
public function __construct(DatabaseInterface $db) |
|
20
|
|
|
{ |
|
21
|
6 |
|
$this->db = $db; |
|
22
|
6 |
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @throws ReflectionException |
|
26
|
|
|
* @throws Exception |
|
27
|
|
|
*/ |
|
28
|
|
|
public function read(string $id): User |
|
29
|
|
|
{ |
|
30
|
|
|
$data = $this->db->select('users')->where('id', $id)->fetch(); |
|
31
|
|
|
if (!$data) { |
|
|
|
|
|
|
32
|
|
|
throw new Exception('not found'); |
|
33
|
|
|
} |
|
34
|
|
|
return User::fromArray($data); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
4 |
|
public function readAll(?QueryInterface $query = null): array |
|
38
|
|
|
{ |
|
39
|
4 |
|
if ($query !== null) { |
|
40
|
4 |
|
$db = $this->db->query($query); |
|
41
|
|
|
} else { |
|
42
|
|
|
$db = $this->db->select('users'); |
|
43
|
|
|
} |
|
44
|
4 |
|
$db->execute(); |
|
45
|
4 |
|
return array_map(fn($data) => User::fromArray($data), $db->fetchAll()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param User $user |
|
50
|
|
|
* @throws Exception |
|
51
|
|
|
*/ |
|
52
|
1 |
|
public function save($user): User |
|
53
|
|
|
{ |
|
54
|
1 |
|
if ($user->getId()) { |
|
55
|
|
|
$id = $user->getId(); |
|
56
|
|
|
$userData = $user->toArray(); |
|
57
|
|
|
unset($userData['id']); |
|
58
|
|
|
$this->db->update('users', $userData)->where('id', $id)->execute(); |
|
59
|
|
|
return $user; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
1 |
|
$this->db->insert('users', $user->toArray())->execute(); |
|
63
|
|
|
|
|
64
|
1 |
|
$lastInsertId = $this->db->lastInsertId(); |
|
65
|
1 |
|
$user->setId($lastInsertId); |
|
66
|
1 |
|
return $user; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @param User $user |
|
71
|
|
|
*/ |
|
72
|
|
|
public function remove($user): int |
|
73
|
|
|
{ |
|
74
|
|
|
$id = $user->getId(); |
|
75
|
|
|
$this->db->delete('users')->where('id', $id)->execute(); |
|
76
|
|
|
return $this->db->rowCount(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.