Skip to content

Instantly share code, notes, and snippets.

@javascripto
Created May 16, 2018 20:12
Show Gist options
  • Select an option

  • Save javascripto/efa46858275cab81307078728512847a to your computer and use it in GitHub Desktop.

Select an option

Save javascripto/efa46858275cab81307078728512847a to your computer and use it in GitHub Desktop.
Servidor JSON Simples com PHP para testes
<?php
header('Content-type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$body = file_get_contents('php://input'); // request body
if (!file_exists('./db.json'))
file_put_contents('db.json', '{}');
$contents = file_get_contents('db.json');
$json = json_decode($contents, true); // true: stdClass => array associativo
if (!array_key_exists('path', $_GET))
die('{"error":"Path missing (?path=resource)"}');
$path = explode('/', $_GET['path']);
if (count($path) == 0 || $path[0] == '')
die('{"error":"Path missing (series/genres)"}');
$param1 = count($path) > 1 ? $path[1] : '';
function findById($array, $id) {
$posicao = -1;
foreach ($array as $key => $value) {
if ($value['id'] == $id) {
$posicao = $key;
break;
}
}
return $posicao;
}
if ($method == 'GET') {
if ($json[$path[0]]) {
if($param1 == '')
echo json_encode($json[$path[0]]);
else {
$posicao = findById($json[$path[0]], $param1);
if ($posicao < 0)
die('{"error":"not found"}');
echo json_encode($json[$path[0]][$posicao]);
}
} else {
echo '[]';
}
}
if ($method == 'POST') {
if (!is_array(json_decode($body, true)))
die('{"error":"body needs to be a valid json"}');
$jsonBody = json_decode($body, true);
$jsonBody['id'] = uniqid();
if(!$json[$path[0]])
$json[$path[0]] = [];
$json[$path[0]][] = $jsonBody;
echo json_encode($jsonBody);
file_put_contents('db.json', json_encode($json));
}
if ($method == 'DELETE') {
if ($json[$path[0]]) {
if($param1 == '')
die('{"error": "missing id"}');
else {
$posicao = findById($json[$path[0]], $param1);
if ($posicao < 0)
die('{"error":"not found"}');
unset($json[$path[0]][$posicao]);
file_put_contents('db.json', json_encode($json));
echo '{"success":"deleted"}';
}
} else {
echo '[]';
}
}
if ($method == 'PUT') {
if ($json[$path[0]]) {
if($param1 == '')
die('{"error": "missing id"}');
else {
$posicao = findById($json[$path[0]], $param1);
if ($posicao < 0)
die('{"error":"not found"}');
if (!is_array(json_decode($body, true)))
die('{"error":"body needs to be a valid json"}');
$jsonBody = json_decode($body, true);
$jsonBody['id'] = $param1;
$json[$path[0]][$posicao] = $jsonBody;
file_put_contents('db.json', json_encode($json));
echo json_encode($jsonBody);
}
} else {
echo '[]';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment