persist user id in json text repository

store userId in the json record and rehydrate the User via
UserRepository. throws DomainException if the referenced user
no longer exists.
This commit is contained in:
Yisroel Baum 2026-05-02 21:27:40 +03:00
parent bac8323806
commit 4635fef3c7
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -5,13 +5,16 @@ namespace App\Text;
use App\Text\Text;
use App\Text\CreateTextDto;
use App\Text\TextRepository;
use App\User\UserRepository;
use DomainException;
class JsonTextRepository implements TextRepository
{
private string $filePath;
public function __construct()
{
public function __construct(
private UserRepository $userRepo,
) {
$this->filePath = __DIR__ . '/../../data/texts.json';
}
@ -20,8 +23,16 @@ class JsonTextRepository implements TextRepository
$texts = $this->readTexts();
$id = $this->getNextId($texts);
$text = new Text(id: $id, name: $dto->name);
$texts[] = ['id' => $id, 'name' => $dto->name];
$text = new Text(
id: $id,
name: $dto->name,
user: $dto->user,
);
$texts[] = [
'id' => $id,
'name' => $dto->name,
'userId' => $dto->user->getId(),
];
$this->writeTexts($texts);
@ -34,10 +45,7 @@ class JsonTextRepository implements TextRepository
foreach ($texts as $data) {
if ($data['id'] === $id) {
return new Text(
id: $data['id'],
name: $data['name'],
);
return $this->hydrate($data);
}
}
@ -53,12 +61,25 @@ class JsonTextRepository implements TextRepository
return array_map(
function (array $data) {
return $this->hydrate($data);
},
$texts
);
}
private function hydrate(array $data): Text
{
$user = $this->userRepo->find($data['userId']);
if ($user === null) {
throw new DomainException(
"User with id: {$data['userId']} doesnt exist"
);
}
return new Text(
id: $data['id'],
name: $data['name'],
);
},
$texts
user: $user,
);
}