Skip to content

Instantly share code, notes, and snippets.

@bmonkman
Last active August 29, 2015 14:10
Show Gist options
  • Save bmonkman/168d85bda2da6f556c41 to your computer and use it in GitHub Desktop.
Save bmonkman/168d85bda2da6f556c41 to your computer and use it in GitHub Desktop.
PHP Dark Launch handler for Consul
#!/usr/local/bin/php
<?php
define('IN_DARKLAUNCH_CONFIG_DIR', '/some/path/');
// Type, e.g. 'core' supplied on the command line by the consul watch
$dlType = $argv[1];
// Get and decode stdin
$data = stream_get_contents(fopen('php://stdin', 'r'));
$consulKVData = json_decode($data, true);
// Convert the json data from stdin into an array
$dlData = [];
foreach ($consulKVData as $row)
{
// Consul base64 encodes the value
$val = json_decode(base64_decode($row['Value']), true);
// Strip everything before dashboard
$prefix = trim(substr($row['Key'], strrpos($row['Key'], 'dashboard/')));
$parts = explode('/', $prefix);
array_shift($parts); // remove dashboard part
array_shift($parts); // remove type part
// typical prefix: /darklaunch/dashboard/core/SOME_CODE
if (sizeof($parts) == 1) {
$dlData[$parts[0]] = $val;
} else { // extended prefix: /darklaunch/dashboard/mobile/APPLE/SOME_CODE
nest($dlData, $parts, $val); // If there are nested items, nest them in the PHP array
}
}
// Structure the content of the php include file (var_export writes the array in php-readable syntax)
$dlFileContents = "<?php\n\return \n\n" . var_export($dlData, true) . ";\n";
// Write the file
@mkdir(IN_DARKLAUNCH_CONFIG_DIR, 0777, true);
$newFile = IN_DARKLAUNCH_CONFIG_DIR."/{$dlType}.php";
$tempFile = $newFile.".".microtime(true);
file_put_contents($tempFile, $dlFileContents, LOCK_EX);
rename($tempFile, $newFile); // Move the whole file once writing is complete
opcache_invalidate($newFile);
// Flush the file from opcache on local webserver if necessary
$ch = curl_init("localhost:80/invalidate-darklaunch");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
curl_close($ch);
// Accept a flat array and nest the entries, ending in a value of $finalValue
// e.g. nest($a, ['one', 'two', 'three'], 'someValue');
// print_r($a);
//Array
//(
// [one] => Array
// (
// [two] => Array
// (
// [three] => someValue
// )
// )
//)
function nest(&$item, $parts, $finalValue) {
$part = array_shift($parts);
if (empty($part)) {
$item = $finalValue;
return;
}
if (!isset($item[$part])) $item[$part] = [];
nest($item[$part], $parts, $finalValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment