diff --git a/src/SlimController/Slim.php b/src/SlimController/Slim.php index 55bcc63..5b6359d 100644 --- a/src/SlimController/Slim.php +++ b/src/SlimController/Slim.php @@ -14,6 +14,8 @@ namespace SlimController; +use Slim\Http\Response; + /** * Extended Slim base */ @@ -171,7 +173,18 @@ protected function buildCallbackFromControllerRoute($route) // Try to fetch the instance from Slim's container, otherwise lazy-instantiate it $instance = $app->container->has($controller) ? $app->container->get($controller) : new $controller($app); - return call_user_func_array(array($instance, $methodName), $args); + $result = call_user_func_array(array($instance, $methodName), $args); + if ($result instanceof Response) { + $container['response'] = $result; + + return true; + } elseif (is_string($result)) { + $container['response'] = new Response($result); + + return true; + } + + return $result; }; return $callable; diff --git a/src/SlimController/SlimController.php b/src/SlimController/SlimController.php index 9c5c526..ce730dc 100644 --- a/src/SlimController/SlimController.php +++ b/src/SlimController/SlimController.php @@ -101,6 +101,25 @@ protected function render($template, $args = array()) $this->app->render($template, $args); } + /** + * Renders given data into JSON string, which is then set as response body + * + * @param mixed $data Data to be encoded into JSON string + * @param int $statusCode HTTP status code + */ + protected function jsonResponse($data, $statusCode = 200) + { + $jsonBody = json_encode($data); + if (json_last_error() !== JSON_ERROR_NONE) { + $this->app->getLog()->error("Failed to encode data to JSON: " . json_last_error_msg()); + + throw new \InvalidArgumentException(json_last_error_msg()); + } + $this->app->response->setBody($jsonBody); + $this->app->response->header('Content-Type', 'application/json'); + $this->app->response->setStatus($statusCode); + } + /** * Performs redirect *