decide.nolog.cz/api/index.php

96 lines
2 KiB
PHP
Raw Normal View History

2015-08-01 18:42:48 +02:00
<?php
/*
* RESTful API used by ember data for data storage
*/
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
require_once 'classes/poll.php';
require_once 'classes/user.php';
require_once 'utils/get-config.php';
$config = getConfig();
define('DATA_FOLDER', $config['dataDir']);
2015-08-01 21:05:22 +02:00
2015-08-01 18:42:48 +02:00
function pollIdIsValid($pollId) {
return preg_match('/[^A-Za-z0-9]/', $pollId) === 0;
}
$app = new \Slim\App(array(
'debug' => $config['debug']
2015-08-22 23:47:31 +02:00
));
2015-08-01 18:42:48 +02:00
// add expires header to all responses to
2015-08-01 18:42:48 +02:00
// prevent Internet Explorer from caching AJAX requests
$app->add(function (Request $request, Response $response, $next) {
$response = $response->withHeader('Expires', '-1');
return $next($request, $response);
});
2015-08-01 18:42:48 +02:00
2015-08-22 23:47:31 +02:00
/*
* api endpoints
*/
$app->get('/polls/{id}', function (Request $request, Response $response) {
$pollId = $request->getAttribute('id');
2015-08-22 23:47:31 +02:00
$poll = Poll::restore($pollId);
2015-08-01 18:42:48 +02:00
2015-08-22 23:47:31 +02:00
if (!$poll) {
return $response->withStatus(404);
2015-08-01 18:42:48 +02:00
}
return $response->withJSON(
array(
'poll' => $poll->export()
2015-08-22 23:47:31 +02:00
)
);
2015-08-01 18:42:48 +02:00
});
$app->post('/polls', function (Request $request, Response $response) {
2015-08-22 23:47:31 +02:00
$poll = Poll::create(
json_decode(
$request->getBody()
2015-08-22 23:47:31 +02:00
)->poll
2015-08-01 18:42:48 +02:00
);
2015-08-22 23:47:31 +02:00
$poll->save();
return $response->withJSON(
array(
'poll' => $poll->export()
2015-08-22 23:47:31 +02:00
)
2015-08-01 18:42:48 +02:00
);
});
$app->post('/users', function (Request $request, Response $response) {
2015-08-22 23:47:31 +02:00
$user = User::create(
json_decode(
$request->getBody()
2015-08-22 23:47:31 +02:00
)->user
2015-08-01 18:42:48 +02:00
);
2015-08-22 23:47:31 +02:00
$user->save();
2015-08-01 18:42:48 +02:00
return $response->withJSON(
array(
'user' => $user->export()
2015-08-22 23:47:31 +02:00
)
2015-08-01 18:42:48 +02:00
);
});
2015-08-22 23:47:31 +02:00
/*
* error handling
*/
$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
return function (Request $request, Response $response, $exception) use ($c) {
return $c['response']->withStatus(500);
};
};
$c['notFoundHandler'] = function ($c) {
return function (Request $request, Response $response) use ($c) {
return $c['response']->withStatus(404);
};
};
2015-08-01 18:42:48 +02:00
$app->run();