feat: add battlefield editor GET and POST handlers
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BattleForge\Http\Handlers;
|
||||
|
||||
use BattleForge\Http\Request;
|
||||
use BattleForge\Http\Response;
|
||||
|
||||
final class GetBattlefieldEditor
|
||||
{
|
||||
/** @param array<string, string> $params */
|
||||
public function handle(Request $request, array $params): Response
|
||||
{
|
||||
$csrf = $request->cookies['__csrf'] ?? '';
|
||||
$scenarioId = $params['id'] ?? 'new';
|
||||
$width = 8;
|
||||
$height = 8;
|
||||
|
||||
ob_start();
|
||||
require_once __DIR__ . '/../../Views/layout.php';
|
||||
require __DIR__ . '/../../Views/battlefield-editor.php';
|
||||
$body = (string) ob_get_clean();
|
||||
|
||||
return Response::html(200, $body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BattleForge\Http\Handlers;
|
||||
|
||||
use BattleForge\Application\ScenarioDraft;
|
||||
use BattleForge\Application\ScenarioSerializer;
|
||||
use BattleForge\Domain\ScenarioValidator;
|
||||
use BattleForge\Http\CsrfToken;
|
||||
use BattleForge\Http\Request;
|
||||
use BattleForge\Http\Response;
|
||||
|
||||
final class PostBattlefieldEditor
|
||||
{
|
||||
/** @param array<string, string> $params */
|
||||
public function handle(Request $request, array $params): Response
|
||||
{
|
||||
$submitted = (string) ($request->server['HTTP_X_CSRF_TOKEN'] ?? '');
|
||||
$expected = (string) ($request->cookies['__csrf'] ?? '');
|
||||
$secret = (string) ($request->server['__csrf_secret'] ?? '');
|
||||
|
||||
if ($secret === '' || $expected === '' || !CsrfToken::verify($submitted, $secret, $expected)) {
|
||||
return Response::json(403, ['error' => 'csrf']);
|
||||
}
|
||||
|
||||
try {
|
||||
$payload = json_decode($request->rawBody, true, flags: JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
return Response::json(400, ['ok' => false, 'errors' => ['Malformed JSON.']]);
|
||||
}
|
||||
|
||||
try {
|
||||
$draft = ScenarioDraft::fromPost($payload);
|
||||
$scenario = $draft->toScenario();
|
||||
ScenarioValidator::validate($scenario);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
return Response::json(400, ['ok' => false, 'errors' => [$exception->getMessage()]]);
|
||||
}
|
||||
|
||||
return Response::json(200, ['ok' => true, 'scenario' => ScenarioSerializer::scenarioToArray($scenario)]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user