Goal-Calibration/app/Plan/UseCases/CreatePlan.php

88 lines
2.4 KiB
PHP

<?php
namespace App\Plan\UseCases;
use App\Exceptions\BadRequestException;
use App\Node\NodeRepository;
use App\Plan\CreatePlanDto;
use App\Plan\Plan;
use App\Plan\PlanRepository;
use App\ScheduledNode\UseCases\CreateScheduledNode;
use App\ScheduledNode\UseCases\CreateScheduledNodeRequest;
use App\Text\TextRepository;
use App\User\UserRepository;
use DateTimeImmutable;
use DomainException;
class CreatePlan
{
public function __construct(
private PlanRepository $planRepo,
private UserRepository $userRepo,
private TextRepository $textRepo,
private NodeRepository $nodeRepo,
private CreateScheduledNode $createScheduledNode,
) {}
/**
* @throws BadRequestException
* @throws DomainException
*/
public function execute(CreatePlanRequest $request): Plan
{
if ($request->userId === null) {
throw new BadRequestException('userId is required');
}
if ($request->textId === null) {
throw new BadRequestException('textId is required');
}
if ($request->name === null) {
throw new BadRequestException('name is required');
}
$userId = $request->userId;
$user = $this->userRepo->find($userId);
if ($user === null) {
throw new DomainException("User with id: $userId doesnt exist");
}
$textId = $request->textId;
$text = $this->textRepo->find($textId);
$nodesOfText = $this->filterForNonParentNodes(
$this->nodeRepo->findByTextId($textId)
);
$plan = $this->planRepo->create(new CreatePlanDto(
name: $request->name,
user: $user,
));
foreach ($nodesOfText as $node) {
$this->createScheduledNode->execute(
new CreateScheduledNodeRequest(
date: new DateTimeImmutable(),
planId: $plan->getId(),
)
);
}
return $plan;
}
/**
* @param Node[] $nodes
* @return Node[]
*/
private function filterForNonParentNodes(array $nodes): array
{
$result = [];
foreach ($nodes as $node) {
$result[$node->getId()] = $node;
$parentNode = $node->getParentNode();
if ($parentNode !== null) {
unset($result[$parentNode->getId()]);
}
}
return array_values($result);
}
}