extend Post entity with feature slot
Adds nullable feature_slot column (unique) plus repo findByFeatureSlot/findFeatured/update methods so admins can pin a post into one of two slots.
This commit is contained in:
parent
64a334c63e
commit
f73e5a1af5
6 changed files with 160 additions and 4 deletions
|
|
@ -5,6 +5,7 @@ namespace Tests\Fakes;
|
|||
use App\Post\CreatePostDto;
|
||||
use App\Post\Post;
|
||||
use App\Post\PostRepository;
|
||||
use RuntimeException;
|
||||
|
||||
class FakePostRepository implements PostRepository
|
||||
{
|
||||
|
|
@ -22,10 +23,11 @@ class FakePostRepository implements PostRepository
|
|||
title: $dto->title,
|
||||
body: $dto->body,
|
||||
createdAt: $dto->createdAt,
|
||||
featureSlot: null,
|
||||
);
|
||||
$this->existingPosts[$id] = $post;
|
||||
|
||||
return $post;
|
||||
return $this->copy($post);
|
||||
}
|
||||
|
||||
public function find(int $id): ?Post
|
||||
|
|
@ -85,6 +87,54 @@ class FakePostRepository implements PostRepository
|
|||
unset($this->existingPosts[$id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function update(Post $post): Post
|
||||
{
|
||||
$id = $post->getId();
|
||||
if (! isset($this->existingPosts[$id])) {
|
||||
throw new RuntimeException(
|
||||
"Post with id: $id does not exist"
|
||||
);
|
||||
}
|
||||
$this->existingPosts[$id] = $post;
|
||||
|
||||
return $this->copy($post);
|
||||
}
|
||||
|
||||
public function findByFeatureSlot(int $slot): ?Post
|
||||
{
|
||||
foreach ($this->existingPosts as $post) {
|
||||
if ($post->getFeatureSlot() === $slot) {
|
||||
return $this->copy($post);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Post[]
|
||||
*/
|
||||
public function findFeatured(): array
|
||||
{
|
||||
$featured = [];
|
||||
foreach ($this->existingPosts as $post) {
|
||||
if ($post->isFeatured()) {
|
||||
$featured[] = $this->copy($post);
|
||||
}
|
||||
}
|
||||
usort(
|
||||
$featured,
|
||||
function (Post $left, Post $right) {
|
||||
return $left->getFeatureSlot() <=> $right->getFeatureSlot();
|
||||
},
|
||||
);
|
||||
|
||||
return $featured;
|
||||
}
|
||||
|
||||
private function copy(Post $post): Post
|
||||
{
|
||||
return new Post(
|
||||
|
|
@ -93,6 +143,7 @@ class FakePostRepository implements PostRepository
|
|||
title: $post->getTitle(),
|
||||
body: $post->getBody(),
|
||||
createdAt: $post->getCreatedAt(),
|
||||
featureSlot: $post->getFeatureSlot(),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue