config = $config; $this->controllerManager = $controllerManager; } public function process(string $route, array $routeParams, RequestWrapper $request, ResponseWrapper $response, array $args) { $response->setHeader('Content-Type', 'application/json'); $params = []; $paramKeys = array_keys($routeParams); $setKeyList = []; foreach ($paramKeys as $key) { $value = $routeParams[$key]; $paramName = $key; if ($value[0] === ':') { $realKey = substr($value, 1); $params[$paramName] = $args[$realKey]; $setKeyList[] = $realKey; } else { $params[$paramName] = $value; } } foreach ($args as $key => $value) { if (in_array($key, $setKeyList)) continue; $params[$key] = $value; } $controllerName = $params['controller'] ?? null; $actionName = $params['action'] ?? null; if (!$controllerName) { throw new Error("Route '{$route}' doesn't have a controller."); } $controllerName = ucfirst($controllerName); $requestMethod = $request->getMethod(); if (!$actionName) { $httpMethod = strtolower($requestMethod); $crudList = $this->config->get('crud') ?? []; $actionName = $crudList[$httpMethod] ?? null; if (!$actionName) { throw new Error("No action for method {$httpMethod}."); } } unset($params['controller']); unset($params['action']); $data = $request->getBodyContents(); if ($data && stristr($request->getContentType(), 'application/json')) { $data = json_decode($data); } $result = $this->controllerManager->process( $controllerName, $requestMethod, $actionName, $params, $data, $request, $response ) ?? null; $responseContents = $result; if ( is_int($result) || is_float($result) || is_array($result) || is_bool($result) || $result instanceof \StdClass ) { $responseContents = Json::encode($result); } if (is_string($responseContents)) { $response->writeBody($responseContents); } $response->setHeader('Expires', '0'); $response->setHeader('Last-Modified', gmdate("D, d M Y H:i:s") . " GMT"); $response->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); $response->setHeader('Pragma', 'no-cache'); } }