DesignPatternsPHP/More/Repository/PostRepository.php
Mario Simão 56970cc221 style: Adopt PSR12
Dev dependency flyeralarm/php-code-validator has been removed.

Closes #444
2021-10-01 10:26:04 -03:00

52 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository;
use OutOfBoundsException;
use DesignPatterns\More\Repository\Domain\Post;
use DesignPatterns\More\Repository\Domain\PostId;
/**
* This class is situated between Entity layer (class Post) and access object layer (Persistence).
*
* Repository encapsulates the set of objects persisted in a data store and the operations performed over them
* providing a more object-oriented view of the persistence layer
*
* Repository also supports the objective of achieving a clean separation and one-way dependency
* between the domain and data mapping layers
*/
class PostRepository
{
public function __construct(private Persistence $persistence)
{
}
public function generateId(): PostId
{
return PostId::fromInt($this->persistence->generateId());
}
public function findById(PostId $id): Post
{
try {
$arrayData = $this->persistence->retrieve($id->toInt());
} catch (OutOfBoundsException $e) {
throw new OutOfBoundsException(sprintf('Post with id %d does not exist', $id->toInt()), 0, $e);
}
return Post::fromState($arrayData);
}
public function save(Post $post)
{
$this->persistence->persist([
'id' => $post->getId()->toInt(),
'statusId' => $post->getStatus()->toInt(),
'text' => $post->getText(),
'title' => $post->getTitle(),
]);
}
}