. */ namespace SP\Core\Bootstrap; use Closure; use Klein\Response; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use SP\Core\HttpModuleBase; use SP\Modules\Api\Init as InitApi; use SP\Services\Api\ApiRequest; use SP\Services\Api\JsonRpcResponse; /** * Bootstrap API interface */ final class BootstrapApi extends BootstrapBase { protected HttpModuleBase $module; /** * @param \Psr\Container\ContainerInterface $container * * @return \SP\Core\Bootstrap\BootstrapApi */ public static function run(ContainerInterface $container): BootstrapApi { logger('------------'); logger('Boostrap:api'); // TODO: remove self::$container = $container; try { /** @noinspection SelfClassReferencingInspection */ $bs = $container->get(BootstrapApi::class); $bs->module = $container->get(InitApi::class); $bs->handleRequest(); return $bs; } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) { processException($e); die($e->getMessage()); } } protected function configureRouter(): void { // Manage requests for api module $this->router->respond( 'POST', '@/api\.php', $this->manageApiRequest() ); } private function manageApiRequest(): Closure { return function ($request, $response, $service) { try { logger('API route'); $apiRequest = self::$container->get(ApiRequest::class); [$controllerName, $action] = explode('/', $apiRequest->getMethod()); $controllerClass = self::getClassFor($controllerName); $method = $action.'Action'; if (!method_exists($controllerClass, $method)) { logger($controllerClass.'::'.$method); /** @var Response $response */ $response->headers() ->set( 'Content-type', 'application/json; charset=utf-8' ); return $response->body( JsonRpcResponse::getResponseError( self::OOPS_MESSAGE, JsonRpcResponse::METHOD_NOT_FOUND, $apiRequest->getId() ) ); } $this->initializeCommon(); $this->module->initialize($controllerName); logger('Routing call: '.$controllerClass.'::'.$method); return call_user_func([new $controllerClass(self::$container, $method), $method]); } catch (\Exception $e) { processException($e); /** @var Response $response */ $response->headers()->set('Content-type', 'application/json; charset=utf-8'); return $response->body(JsonRpcResponse::getResponseException($e, 0)); } finally { $this->router->skipRemaining(); } }; } }