65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Plan;
|
|
|
|
use App\Exceptions\BadRequestException;
|
|
use App\Plan\UseCases\CreatePlan;
|
|
use App\Plan\UseCases\CreatePlanRequest;
|
|
use App\User\User;
|
|
use DomainException;
|
|
use Psr\Http\Message\ResponseInterface as Response;
|
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
|
|
|
class PlanController
|
|
{
|
|
public function createPlan(
|
|
Request $request,
|
|
Response $response,
|
|
CreatePlan $createPlanUseCase,
|
|
): Response {
|
|
$user = $request->getAttribute('user');
|
|
if (!$user instanceof User) {
|
|
$response->getBody()->write(
|
|
json_encode(['error' => 'unauthenticated'])
|
|
);
|
|
return $response->withStatus(401)
|
|
->withHeader('Content-Type', 'application/json');
|
|
}
|
|
|
|
$data = json_decode((string) $request->getBody(), true) ?? [];
|
|
|
|
$textId = isset($data['textId']) ? (int) $data['textId'] : null;
|
|
$name = $data['name'] ?? null;
|
|
$dateStart = $data['dateStart'] ?? null;
|
|
$dateEnd = $data['dateEnd'] ?? null;
|
|
|
|
try {
|
|
$plan = $createPlanUseCase->execute(new CreatePlanRequest(
|
|
userId: $user->getId(),
|
|
textId: $textId,
|
|
name: $name,
|
|
dateStart: $dateStart,
|
|
dateEnd: $dateEnd,
|
|
));
|
|
} catch (BadRequestException $exception) {
|
|
$response->getBody()->write(
|
|
json_encode(['error' => $exception->getMessage()])
|
|
);
|
|
return $response->withStatus(400)
|
|
->withHeader('Content-Type', 'application/json');
|
|
} catch (DomainException $exception) {
|
|
$response->getBody()->write(
|
|
json_encode(['error' => $exception->getMessage()])
|
|
);
|
|
return $response->withStatus(404)
|
|
->withHeader('Content-Type', 'application/json');
|
|
}
|
|
|
|
$response->getBody()->write(json_encode([
|
|
'id' => $plan->getId(),
|
|
'name' => $plan->getName(),
|
|
]));
|
|
return $response->withStatus(201)
|
|
->withHeader('Content-Type', 'application/json');
|
|
}
|
|
}
|