Last active
August 29, 2015 14:06
-
-
Save Hais/d410fb296df16667f96a to your computer and use it in GitHub Desktop.
CannedREST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Run as: | |
# php -S 0.0.0.0:80 -t . index.php | |
# A GET Request of | |
# http://127.0.0.1/3/en/mobile/merchant/nearby?longitude=-0.127758&latitude=51.5073509&merchant_id=123 | |
# Would output the contents of | |
# ./repo/get/3/en/mobile/merchant/nearby/latitude=51.5073509&longitude=-0.127758&merchant_id=123.json | |
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); | |
$vars = $_REQUEST; | |
if (array_key_exists("betatester", $vars)) { | |
unset($vars["betatester"]); | |
} | |
// Sort variables alphabetically so that the order of the params is irrelevant | |
ksort($vars); | |
// Allow override of HTTP Method if var is set | |
$method = @$vars['http_method'] ?: $_SERVER['REQUEST_METHOD']; | |
unset($vars['http_method']); | |
// Build the file path | |
// If no params exist then look for '_default.json' | |
$query = http_build_query($vars); | |
if (!strlen($query)) { | |
$query = '_default'; | |
} | |
$extensions = ["json" => "application/json", "html" => "text/html"]; | |
$path = __DIR__ . '/repo/' . strtolower($method) . $path . '/' . $query; | |
$found = false; | |
foreach ($extensions as $extension => $mime) { | |
$file = $path . ".{$extension}"; | |
if (!$found && $realpath = realpath($file)) { | |
$found = true; | |
header("Content-type: {$mime}"); | |
$handle = @fopen($realpath, "r"); | |
if ($handle) { | |
while (($buffer = fgets($handle, 4096)) !== false) { | |
if (!headers_sent() && ctype_alnum(substr($buffer, 0, 1))) { | |
$buffer = trim($buffer); | |
if (is_numeric($buffer)) { | |
http_response_code($buffer); | |
} else { | |
header($buffer); | |
} | |
} else { | |
echo $buffer; | |
} | |
} | |
fclose($handle); | |
} | |
} | |
} | |
if (!$found) { | |
http_response_code(500); | |
header("Content-type: text/plain"); | |
$extensions_str = implode("|", array_keys($extensions)); | |
echo "Couldn't find response. Expecting: {$path}.[{$extensions_str}]"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment