implement SetFeaturedPost use case
This commit is contained in:
parent
13ca655f9b
commit
ee95bcafc9
2 changed files with 81 additions and 0 deletions
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
namespace App\Post\UseCases\SetFeaturedPost;
|
||||
|
||||
use App\Exceptions\BadRequestException;
|
||||
use App\Exceptions\ForbiddenException;
|
||||
use App\Post\Post;
|
||||
use App\Post\PostRepository;
|
||||
use DomainException;
|
||||
|
||||
class SetFeaturedPost
|
||||
{
|
||||
private const VALID_SLOTS = [1, 2];
|
||||
|
||||
public function __construct(
|
||||
private PostRepository $postRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws BadRequestException
|
||||
* @throws ForbiddenException
|
||||
* @throws DomainException
|
||||
*/
|
||||
public function execute(SetFeaturedPostRequest $request): Post
|
||||
{
|
||||
if (! $request->requesterIsAdmin) {
|
||||
throw new ForbiddenException(
|
||||
'only admins can feature a post'
|
||||
);
|
||||
}
|
||||
if ($request->postId <= 0) {
|
||||
throw new BadRequestException('postId must be positive');
|
||||
}
|
||||
if (! in_array($request->slot, self::VALID_SLOTS, true)) {
|
||||
throw new BadRequestException(
|
||||
'slot must be 1 or 2'
|
||||
);
|
||||
}
|
||||
|
||||
$post = $this->postRepo->find($request->postId);
|
||||
if ($post === null) {
|
||||
throw new DomainException('post not found');
|
||||
}
|
||||
|
||||
$existingInSlot = $this->postRepo->findByFeatureSlot($request->slot);
|
||||
if (
|
||||
$existingInSlot !== null
|
||||
&& $existingInSlot->getId() !== $post->getId()
|
||||
) {
|
||||
$this->postRepo->update(new Post(
|
||||
id: $existingInSlot->getId(),
|
||||
userId: $existingInSlot->getUserId(),
|
||||
title: $existingInSlot->getTitle(),
|
||||
body: $existingInSlot->getBody(),
|
||||
createdAt: $existingInSlot->getCreatedAt(),
|
||||
featureSlot: null,
|
||||
));
|
||||
}
|
||||
|
||||
return $this->postRepo->update(new Post(
|
||||
id: $post->getId(),
|
||||
userId: $post->getUserId(),
|
||||
title: $post->getTitle(),
|
||||
body: $post->getBody(),
|
||||
createdAt: $post->getCreatedAt(),
|
||||
featureSlot: $request->slot,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
namespace App\Post\UseCases\SetFeaturedPost;
|
||||
|
||||
class SetFeaturedPostRequest
|
||||
{
|
||||
public function __construct(
|
||||
public int $postId,
|
||||
public int $slot,
|
||||
public bool $requesterIsAdmin,
|
||||
) {}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue