Content-Negotiation with the help of Renderer and Formatters

This commit is contained in:
Gilles Crettenand
2015-06-02 02:02:40 +02:00
parent c0159f4b79
commit 7e0a38e989
7 changed files with 241 additions and 23 deletions

View File

@@ -3,6 +3,7 @@
namespace BSR\Lib;
use BSR\Lib\Exception\WebException;
use BSR\Lib\Renderer;
abstract class WebService
{
@@ -30,6 +31,8 @@ abstract class WebService
public function Run()
{
$renderer = new Renderer();
$this->log("------------------");
$this->log("Start request", 1, true);
$data = array();
@@ -39,19 +42,22 @@ abstract class WebService
$data["result"][$this->func] = $result;
} catch (WebException $e) {
$data["error"]["code"] = $e->getCode();
$data["error"]["name"] = $e->getName();
$data["error"]["reason"] = $e->getMessage();
$data["error"]["name"] = $e->getName();
$this->status = 400;
$this->log(sprintf("Error : [%s] %s", $e->getCode(), $e->getName()));
} catch (\Exception $e) {
$data["failure"]["message"] = $e->getMessage();
$data["failure"]["code"] = $e->getCode();
$data["failure"]["reason"] = $e->getMessage();
$this->status = 500;
$this->log(sprintf("Failure : %s", $e->getMessage()));
}
$this->Send($data);
$this->log("Data: ".print_r($data, true), 2);
$renderer->render($this->status, $data);
$this->log("Request finished", 1, true);
$this->log("------------------\n\n");
@@ -63,7 +69,6 @@ abstract class WebService
private function Call()
{
ob_start();
session_save_path(Configuration::get('session.save_path'));
session_start();
@@ -100,23 +105,4 @@ abstract class WebService
$this->log("Params: ".print_r($params, true), 2);
return call_user_func_array(array($this, $this->func), $params);
}
private function Send(array $data)
{
static $status_messages = array(
200 => 'Ok',
400 => 'Bad request',
404 => 'Not Found',
403 => 'Not Authorized',
500 => 'Server Error',
);
header(sprintf('HTTP/1.0 %s %s', $this->status, $status_messages[$this->status]));
ob_clean();
flush();
$this->log("Data: ".print_r($data, true), 2);
echo json_encode($data);
}
}