Skip to content

Instantly share code, notes, and snippets.

@piiskop
Created March 20, 2018 20:55
Show Gist options
  • Save piiskop/944b88d16607d2ddbcb0001ec452910b to your computer and use it in GitHub Desktop.
Save piiskop/944b88d16607d2ddbcb0001ec452910b to your computer and use it in GitHub Desktop.
<?php
namespace pupils;
class PupilController {
public function __construct() {
require_once dirname(__FILE__) . '/Pupil.php';
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET' :
{
if (isset($_GET['id'])) {
$data = Pupil::find(
array (
'where' => array (
'idPupil' => array (
'=' => $_GET['id']
)
)
));
} else {
$data = Pupil::find(array ());
}
if (isset($_GET['format'])) {
switch ($_GET['format']) {
case 'json' :
{
if (sizeof($data) > 0) {
new \o\Response(array (
'data' => $data,
'message' => 'number of pupils found: ' . $_SESSION['dbEngine']->getNumberOfRecords(),
'status' => 200
));
} else {
new \o\Response(array (
'message' => 'no pupils found',
'status' => 204
));
}
}
default :
{
new \o\Response(array (
// @formatter:off
'message' => sprintf(
'Vormindus %1$s on mulle tundmatu.',
$_GET['format'] // 1
),
// @formatter:on
'status' => 415
));
}
}
} else {
new \o\Response(array (
'message' => 'This application doesn\'t talk to humans yet. Please use format=json in your querystring.',
'status' => 501
));
}
}
case 'POST' :
{
if (isset($_GET['format'])) {
switch ($_GET['format']) {
case 'json' :
{
$data = json_decode(
file_get_contents("php://input", true));
if (isset($data->batch)) {
Pupil::insert(
array (
'batch' => $data->batch
));
new \o\Response(array (
'message' => 'Number of pupils inserted: ' . sizeof(
$data->batch),
'status' => 201
));
} else {
new \o\Response(array (
'message' => 'In input array, the index batch must be present and that has the array of items.',
'status' => 415
));
}
}
default :
{
new \o\Response(array (
// @formatter:off
'message' => sprintf(
'Vormindus %1$s on mulle tundmatu.',
$_GET['format'] // 1
),
// @formatter:on
'status' => 415
));
}
}
} else {
new \o\Response(array (
'message' => 'This application doesn\'t talk to humans yet. Please use format=json in your querystring.',
'status' => 501
));
}
}
case 'PUT' :
{
$data = json_decode(file_get_contents("php://input", true));
$pupil = new Pupil(array (
'id' => $data->id
));
if (isset($data->name)) {
$pupil->setName($data->name);
}
if (isset($data->folder)) {
$pupil->setFolder($data->folder);
}
if (isset($data->idStudyGroup)) {
$pupil->setStudyGroup($data->idStudyGroup);
}
$pupil->update();
new \o\Response(array (
// @formatter:off
'message' => sprintf(
'The pupil %1$s is up to date.',
htmlentities($pupil->getName(), ENT_HTML5, 'UTF-8') // 1
),
// @formatter:on
'status' => 204
));
}
default :
{
new \o\Response(array (
'message' => 'unknown request method: ',
$_SERVER['REQUEST_METHOD'],
'status' => 405
));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment