Skip to content

Instantly share code, notes, and snippets.

@Plopix
Last active July 29, 2021 21:59
Show Gist options
  • Save Plopix/05af446c2a37d1e77804a013e2fd31d9 to your computer and use it in GitHub Desktop.
Save Plopix/05af446c2a37d1e77804a013e2fd31d9 to your computer and use it in GitHub Desktop.
Convert Platform.sh Redirect to Table for Fastly
<?php
require __DIR__.'./../../../ezplatform/vendor/autoload.php';
// At least one table
$tableCount = 1;
// to skip the N first routes
$skipFirst = getenv('SKIP') ? : 0;
$projectName = getenv('PROJECTNAME') ? : 'project';
$route = getenv('ROUTE') ? : 'https://{default}/';
$limit = getenv('LIMIT') ? : 1000;
$domain = getenv('DOMAIN') ? : '{default}';
$tablePrefix = $projectName.'_redirects_list';
$inBlock = function ($blockName, $lines) {
$string = "{$blockName} {".PHP_EOL;
foreach ($lines as $line) {
$string .= "\t{$line}".PHP_EOL;
}
$string .= '}'.PHP_EOL;
return $string;
};
$count = 0;
$routes = Symfony\Component\Yaml\Yaml::parse(file_get_contents(__DIR__.'/../../../.platform/routes.yaml'));
$redirects = $routes[$route]['redirects']['paths'];
// # TABLE CREATION
$tables = [];
$rows = [];
foreach ($redirects as $from => ['to' => $to]) {
if ($count < $skipFirst) {
$count++;
continue;
}
$cleanTo = str_replace("{default}", $domain, $to);
$rows[] = "\"{$from}\": \"{$cleanTo}\",";
if (\count($rows) >= $limit) {
$tables[] = "{$tablePrefix}{$tableCount}";
print $inBlock("table {$tablePrefix}{$tableCount}", $rows);
$rows = [];
$tableCount++;
}
$count++;
}
$tables[] = "{$tablePrefix}{$tableCount}";
print $inBlock("table {$tablePrefix}{$tableCount}", $rows);
// # VCL_RECV
$rows = [];
foreach ($tables as $table) {
$rows[] = "if (table.lookup({$table}, req.url.path)) { error 618 \"{$table}\"; }";
}
print $inBlock('sub vcl_recv', $rows);
// # VCL_ERROR
print $inBlock('sub vcl_error',
array_map(fn($table) => $inBlock("if (obj.status == 618 && obj.response == \"{$table}\")",
[
"\tset obj.status = 301;",
"\tset obj.http.Location = table.lookup({$table}, req.url.path);",
"\treturn (deliver);"
]),
$tables)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment