decide.nolog.cz/api/index.php

98 lines
1.6 KiB
PHP
Raw Normal View History

2015-08-01 18:42:48 +02:00
<?php
/*
* RESTful API used by ember data for data storage
*/
2015-08-01 21:05:22 +02:00
if (php_sapi_name() == 'cli-server') {
// assume that cli-server is only used for testing
define('DATA_FOLDER', 'tests/_tmp/data/');
}
else {
define('DATA_FOLDER', '../data/');
}
2015-08-01 18:42:48 +02:00
require 'vendor/autoload.php';
2015-08-22 23:47:31 +02:00
require_once 'classes/poll.php';
require_once 'classes/user.php';
2015-08-01 18:42:48 +02:00
function pollIdIsValid($pollId) {
return preg_match('/[^A-Za-z0-9]/', $pollId) === 0;
}
2015-08-22 23:47:31 +02:00
$app = new \Slim\Slim(array(
'debug' => false
));
2015-08-01 18:42:48 +02:00
/*
* default response headers
*/
$app->response->headers->set('Content-Type', 'application/json; charset=utf-8');
// prevent Internet Explorer from caching AJAX requests
$app->expires('-1');
2015-08-22 23:47:31 +02:00
/*
* api endpoints
*/
2015-08-01 18:42:48 +02:00
$app->get('/polls/:id', function ($pollId) use ($app) {
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) {
$app->halt(404);
2015-08-01 18:42:48 +02:00
}
2015-08-22 23:47:31 +02:00
$app->response->setBody(
json_encode(
array(
'poll' => $poll->export()
)
)
);
2015-08-01 18:42:48 +02:00
});
$app->post('/polls', function() use ($app) {
2015-08-22 23:47:31 +02:00
$poll = Poll::create(
json_decode(
$app->request->getBody()
)->poll
2015-08-01 18:42:48 +02:00
);
2015-08-22 23:47:31 +02:00
$poll->save();
2015-08-01 18:42:48 +02:00
$app->response->setBody(
2015-08-22 23:47:31 +02:00
json_encode(
array(
'poll' => $poll->export()
)
)
2015-08-01 18:42:48 +02:00
);
});
$app->post('/users', function() use ($app) {
2015-08-22 23:47:31 +02:00
$user = User::create(
json_decode(
$app->request->getBody()
)->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
$app->response->setBody(
2015-08-22 23:47:31 +02:00
json_encode(
array(
'user' => $user->export()
)
)
2015-08-01 18:42:48 +02:00
);
});
2015-08-22 23:47:31 +02:00
/*
* error handling
*/
$app->error(function() use ($app) {
$app->halt(500);
});
$app->notFound(function() use ($app) {
$app->halt(404);
2015-08-01 18:42:48 +02:00
});
$app->run();