add json user repository
This commit is contained in:
parent
895bfb01da
commit
3595bcbf11
1 changed files with 84 additions and 0 deletions
84
app/User/JsonUserRepository.php
Normal file
84
app/User/JsonUserRepository.php
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\User;
|
||||||
|
|
||||||
|
use App\User\UseCases\CreateUserDto;
|
||||||
|
use App\ValueObjects\EmailAddress;
|
||||||
|
|
||||||
|
class JsonUserRepository implements UserRepository
|
||||||
|
{
|
||||||
|
private string $filePath;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->filePath = __DIR__ . '/../../data/users.json';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(CreateUserDto $dto): User
|
||||||
|
{
|
||||||
|
$users = $this->readUsers();
|
||||||
|
$id = $this->getNextId($users);
|
||||||
|
|
||||||
|
$users[] = [
|
||||||
|
'id' => $id,
|
||||||
|
'email' => (string) $dto->email,
|
||||||
|
];
|
||||||
|
$this->writeUsers($users);
|
||||||
|
|
||||||
|
return new User(
|
||||||
|
id: $id,
|
||||||
|
email: $dto->email,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function find(int $id): ?User
|
||||||
|
{
|
||||||
|
$users = $this->readUsers();
|
||||||
|
|
||||||
|
foreach ($users as $data) {
|
||||||
|
if ($data['id'] === $id) {
|
||||||
|
return new User(
|
||||||
|
id: $data['id'],
|
||||||
|
email: new EmailAddress($data['email']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function readUsers(): array
|
||||||
|
{
|
||||||
|
if (!file_exists($this->filePath)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$content = file_get_contents($this->filePath);
|
||||||
|
|
||||||
|
return json_decode($content, true) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function writeUsers(array $users): void
|
||||||
|
{
|
||||||
|
file_put_contents(
|
||||||
|
$this->filePath,
|
||||||
|
json_encode($users, JSON_PRETTY_PRINT)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getNextId(array $users): int
|
||||||
|
{
|
||||||
|
if (empty($users)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$maxId = -1;
|
||||||
|
foreach ($users as $user) {
|
||||||
|
if ($user['id'] > $maxId) {
|
||||||
|
$maxId = $user['id'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $maxId + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue