Created
July 13, 2016 10:58
-
-
Save kingster/37807625ad532018af41ce7cbc575631 to your computer and use it in GitHub Desktop.
Swagger Cache
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 | |
// Access-Control headers are received during OPTIONS requests | |
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { | |
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) | |
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); | |
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) | |
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); | |
exit(0); | |
} | |
header('Content-Type: text/plain; charset=utf-8'); | |
// Allow from any origin | |
if (isset($_SERVER['HTTP_ORIGIN'])) { | |
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one | |
// you want to allow, and if so: | |
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); | |
header('Access-Control-Allow-Credentials: true'); | |
header('Access-Control-Max-Age: 86400'); // cache for 1 day | |
} | |
$cacheFile = "swagger.cache"; | |
if (file_exists($cacheFile)) { | |
if(filemtime($cacheFile) + 600 > time()){ | |
//cache hit | |
$data = file_get_contents($cacheFile); | |
echo $data; | |
} else { | |
//cache miss | |
$data = getUpdatedSwaggerDoc(); | |
$file = fopen($cacheFile,"w"); | |
echo fwrite($file,$data); | |
fclose($file); | |
echo $data; | |
} | |
} else { | |
$data = getUpdatedSwaggerDoc(); | |
$file = fopen($cacheFile,"w"); | |
echo fwrite($file,$data); | |
fclose($file); | |
echo $data; | |
} | |
function getUpdatedSwaggerDoc(){ | |
// create curl resource | |
$ch = curl_init(); | |
// set url | |
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/flipkart/connekt/contents/schema/swagger-api.yaml"); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: token <token>', 'Accept: application/vnd.github.v3.raw', 'User-Agent: php-cli')); | |
//return the transfer as a string | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
// $output contains the output string | |
$output = curl_exec($ch); | |
// close curl resource to free up system resources | |
curl_close($ch); | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment