From 4635fef3c71cb81bc79d1f99a3545b53f2a478cf Mon Sep 17 00:00:00 2001 From: Yisroel Baum Date: Sat, 2 May 2026 21:27:40 +0300 Subject: [PATCH] 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. --- app/Text/JsonTextRepository.php | 45 ++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/app/Text/JsonTextRepository.php b/app/Text/JsonTextRepository.php index 26c5e76..23c612d 100644 --- a/app/Text/JsonTextRepository.php +++ b/app/Text/JsonTextRepository.php @@ -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,15 +61,28 @@ class JsonTextRepository implements TextRepository return array_map( function (array $data) { - return new Text( - id: $data['id'], - name: $data['name'], - ); + 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'], + user: $user, + ); + } + /** * @return array */