0
1
Fork 0
hedera-web-mindshore/vn/web/json-request.php

84 lines
1.6 KiB
PHP
Raw Normal View History

2016-07-22 20:00:27 +00:00
<?php
namespace Vn\Web;
require_once (__DIR__.'/http-request.php');
require_once (__DIR__.'/json-reply.php');
require_once (__DIR__.'/json-message.php');
/**
* Base class for rest services.
**/
class JsonRequest extends HttpRequest
{
function listen ()
{
try {
// Checks the client version
if (!empty ($_COOKIE['vn_version']))
$clientVersion = (int) $_COOKIE['vn_version'];
if (isset ($clientVersion)
&& $clientVersion < $this->getVersion ())
throw new Lib\UserException (s('Critical version available'), 'newVersion');
// Fetchs the result
$json = $this->run ();
$this->json ($json);
}
catch (SessionExpiredException $e)
{
$this->setError (s('The session has expired'), 'sessionExpired');
}
catch (BadLoginException $e)
{
$this->setError (s('Invalid login'), 'badLogin');
}
catch (Lib\UserException $e)
{
$this->setError ($e->getMessage (), $e->getCode ());
}
}
function json ($json)
{
$reply = new JsonReply ();
$reply->data = $json;
if ($this->warnings)
{
$reply->warnings = [];
foreach ($this->warnings as $warning)
$reply->warnings = $warning;
}
$this->replyJson ($reply);
}
function replyJson ($reply)
{
header ('Content-Type: application/json; charset=UTF-8');
echo json_encode ($reply);
}
function addWarning ($message, $code)
{
if (!isset ($this->reply->warnings))
$this->reply->warnings = [];
$this->warnings[] = new JsonMessage ($code, $message);
}
function setError ($message, $code)
{
http_response_code (400);
$reply = new JsonMessage ($code, $message);
$this->replyJson ($reply);
}
}
?>