Skip to content
This repository was archived by the owner on Sep 19, 2022. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/SlimController/Slim.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

namespace SlimController;

use Slim\Http\Response;

/**
* Extended Slim base
*/
Expand Down Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions src/SlimController/SlimController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down