Logic to handle "GET Candidates"
[asis23-votoe-server.git] / rest-api.php
blob2fe6abf4073400a4edc9ccfa82e1e1610d308b6e
1 <?php
3 // Response 'Content-Type' header
4 header('Content-Type: application/json');
6 // Flag that tells if the 'Accept' header in the request is invalid
7 $invalidAccept = '*/*' != $_SERVER['HTTP_ACCEPT'] && 'application/json' != $_SERVER['HTTP_ACCEPT'];
9 // Do not accept requests which 'Accept' header isn't one of the above
10 if ($invalidAccept) {
11 header('HTTP/1.1 406 Not Acceptable');
12 exit;
15 // Get request method and path
16 $method = strtolower($_SERVER['REQUEST_METHOD']);
17 $uri = parse_url($_SERVER['REQUEST_URI']);
18 $path = trim(trim($uri['path']), '/');
20 // Default 'resource' and 'id' values
21 $resource = 'root';
22 $id = null;
24 // Get 'resource' and 'id' values
25 if ($path) {
26 $path = explode('/', $path);
27 $resource = $path[0];
28 if (!empty($path[1])) {
29 $id = (int) $path[1];
33 // Default 'input' value
34 $input = null;
36 // Get 'input' value
37 if ('post' == $method || 'put' == $method) {
38 $input = file_get_contents('php://input');
41 // File name (convention) from where the logic will be loaded
42 $fileName = strtolower("{$method}_{$resource}");
43 $fileName.= $id ? '_id' : '';
44 $fileName.= '.php';
46 // Function name (convention) that handles the request
48 // The function will receive the following parameters:
50 // * Parameter 1: int|null $id The item ID (if it's present)
51 // * Parameter 2: string|null $input The input value (if it's present)
52 $functionName = 'handle_request';
54 // Load and call the logic that handles the request
55 if (is_readable($fileName)) {
56 require_once($fileName);
57 if (function_exists($functionName)) {
58 $functionName($id, $input);
59 exit;
63 // Default (404) response code
64 header('HTTP/1.1 404 Not Found');