69 lines
2 KiB
PHP
69 lines
2 KiB
PHP
<?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,
|
|
));
|
|
}
|
|
}
|