diff --git a/SeacmsApi.php b/SeacmsApi.php index cb13386..637932e 100644 --- a/SeacmsApi.php +++ b/SeacmsApi.php @@ -6,6 +6,7 @@ use SeaCMS\Api\ApiAware; use SeaCMS\Api\BadMethodException; use SeaCMS\Api\Cookies; use SeaCMS\Api\JsonResponse; +use SeaCMS\Api\LateApiAware; use SeaCMS\Api\NotFoundRouteException; use SeaCMS\Api\SpecialOutputException; @@ -123,7 +124,17 @@ class SeacmsApi extends AbstractPicoPlugin implements ApiAware if (is_array($routes)){ foreach($routes as $route => $methodName){ if (is_string($methodName) && method_exists($plugin,$methodName)){ - $this->routes[$route] = [$plugin,$methodName]; + $this->routes[$route] = [$plugin,$methodName,false]; + } + } + } + if ($plugin instanceof LateApiAware){ + $routes = $plugin->registerLateApiRoutes(); + if (is_array($routes)){ + foreach($routes as $route => $methodName){ + if (is_string($methodName) && method_exists($plugin,$methodName)){ + $this->routes[$route] = [$plugin,$methodName,true]; + } } } } @@ -162,6 +173,9 @@ class SeacmsApi extends AbstractPicoPlugin implements ApiAware */ public function onPageRendered(&$output) { + if ($this->resolveApi($output,true)){ + $output = $output->send(); + } if (JsonResponse::canSendHeaders()){ $this->getCookies()->sendCookiesOnce(); } @@ -170,9 +184,10 @@ class SeacmsApi extends AbstractPicoPlugin implements ApiAware /** * resolve api * @param null|string|JsonResponse $output + * @param bool $isLate * @return bool $outputChanged */ - protected function resolveApi(&$output): bool + protected function resolveApi(&$output, bool $isLate = false): bool { $outputChanged = false; if (isset($_GET['api'])){ @@ -197,6 +212,14 @@ class SeacmsApi extends AbstractPicoPlugin implements ApiAware $response = null; try { $data = $this->searchCorrespondingRoute($route); + if ($data['isLate'] !== $isLate){ + if ($isLate){ + return new Exception('Calling an api route but catch onPageRedered whereas should be caught onThemeLoading !'); + } else { + ob_end_clean(); + return false; + } + } $response = call_user_func_array([$data['plugin'],$data['methodName']],$data['params']); if (!($response instanceof JsonResponse)){ $response = null; @@ -275,7 +298,8 @@ class SeacmsApi extends AbstractPicoPlugin implements ApiAware return [ 'plugin' => $data[0], 'methodName' => $data[1], - 'params' => $params + 'params' => $params, + 'isLate' => $data[2] ]; } elseif (!$badMethod && array_key_exists((($method == 'GET') ? 'POST' : 'GET' )." $searchingRoute",$this->routes)){ $badMethod = true; diff --git a/src/LateApiAware.php b/src/LateApiAware.php new file mode 100644 index 0000000..4e46f33 --- /dev/null +++ b/src/LateApiAware.php @@ -0,0 +1,19 @@ +