ai_analysis/src/Api/ApiKernel.php

114 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Api;
use App\Controller\HealthController;
use App\Controller\StatsController;
use App\Http\HttpRequest;
use App\Http\JsonResponse;
use App\Tools\AnalyzeOfflineOrdersTool;
use App\Tools\MerchantRankingTool;
use App\Tools\OrderSummaryTool;
final readonly class ApiKernel
{
public function __construct(
private HealthController $healthController,
private StatsController $statsController,
) {
}
public function handle(HttpRequest $request): void
{
try {
match ($request->path) {
'/', '/health' => $this->ok($this->healthController->show()),
'/tools' => $this->ok($this->tools()),
'/api/order-summary' => $this->post($request, fn (): array => $this->statsController->orderSummary($request)),
'/api/offline-stats' => $this->post($request, fn (): array => $this->statsController->offlineStats($request)),
'/api/merchant-ranking' => $this->post($request, fn (): array => $this->statsController->merchantRanking($request)),
default => JsonResponse::send([
'success' => false,
'error' => [
'code' => 'not_found',
'message' => 'API route not found.',
],
], 404),
};
} catch (\Throwable $exception) {
JsonResponse::send([
'success' => false,
'error' => [
'code' => 'server_error',
'message' => $exception->getMessage(),
],
], 500);
}
}
/**
* @param \Closure(): array<string, mixed> $handler
*/
private function post(HttpRequest $request, \Closure $handler): void
{
if ($request->method !== 'POST') {
JsonResponse::send([
'success' => false,
'error' => [
'code' => 'method_not_allowed',
'message' => 'This endpoint only supports POST.',
],
], 405);
return;
}
$this->ok($handler());
}
/**
* @param array<string, mixed> $data
*/
private function ok(array $data): void
{
JsonResponse::send([
'success' => true,
'data' => $data,
]);
}
/**
* @return array<string, mixed>
*/
private function tools(): array
{
return [
'tools' => [
[
'name' => OrderSummaryTool::NAME,
'description' => OrderSummaryTool::DESCRIPTION,
'method' => 'POST',
'path' => '/api/order-summary',
'inputSchema' => OrderSummaryTool::inputSchema(),
],
[
'name' => AnalyzeOfflineOrdersTool::NAME,
'description' => AnalyzeOfflineOrdersTool::DESCRIPTION,
'method' => 'POST',
'path' => '/api/offline-stats',
'inputSchema' => AnalyzeOfflineOrdersTool::inputSchema(),
],
[
'name' => MerchantRankingTool::NAME,
'description' => MerchantRankingTool::DESCRIPTION,
'method' => 'POST',
'path' => '/api/merchant-ranking',
'inputSchema' => MerchantRankingTool::inputSchema(),
],
],
];
}
}