Skip to content

Instantly share code, notes, and snippets.

@gskema
Last active January 10, 2017 15:08
Show Gist options
  • Save gskema/2e2ce6584737a3b66351e6ec77e8ce20 to your computer and use it in GitHub Desktop.
Save gskema/2e2ce6584737a3b66351e6ec77e8ce20 to your computer and use it in GitHub Desktop.
ElasticSearch escape date math index names in request path
<?php
// @see https://www.elastic.co/guide/en/elasticsearch/reference/5.x/date-math-index-names.html
// @TODO <elastic\\{ON\\}-{now/M}>
function escapePathWithDateMath($path)
{
$symbols = ['<', '>', '/', '{', '}', '|', '+', ':', ','];
$escaped = ['%3C', '%3E', '%2F', '%7B', '%7D', '%7C', '%2B', '%3A', '%2C'];
// Check if the string is already escaped
if (strpos(strtoupper($path), '%2F')) {
return $path;
}
// Check if date math if used at all. E.g. /<log-{now/d}>/log/_refresh
$pos1 = strpos($path, '>');
if (false === $pos1) {
return $path;
}
// Check if path starts with string and trim it, e.g. /<log-{now/d}>/log/_refresh
if ($startsWithSlash = '/' === $path[0]) {
$path = ltrim($path, '/');
// Adjust positions we calculated previously
$pos1--;
}
// Find the position up to which we should escape. Should be next slash / after > E.g. <log-{now/d}>/log/_refresh
$pos2 = strrpos($path, '/', $pos1);
$pos2 = false !== $pos2 ? $pos2 : strlen($path);
// Cut out the bit we need to escape: <log-{now/d}>
$segment = substr($path, 0, $pos2 - 1);
// Escape using character map
$escapedSegment = str_replace($symbols, $escaped, $segment);
// Replace part of the string. E.g. /%3Clog-%7Bnow%2Fd%7D%3E/log/_refresh
$path = substr_replace($path, $escapedSegment, 0, $pos2 - 1);
// Prefix with / if it was there before
return ($startsWithSlash ? '/' : '').$path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment