Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to condense Jekyll front matter for Jigsaw
<?php
require 'vendor/autoload.php';
$parser = new \Mni\FrontYAML\Parser();
$config = [
'whitelist' => ['title', 'excerpt', 'comments', 'categories', 'seo_image'],
'merge' => [
'extends' => '_layouts.post',
'section' => 'content',
'date' => 'generate_date',
'categories' => 'verify_categories'
]
];
foreach (new DirectoryIterator('source/_posts') as $file) {
if (!$file->isFile()) {
continue;
}
$contents = file_get_contents($file->getRealPath());
$document = $parser->parse($contents, false);
$front_matter = $document->getYAML();
$refined = array_filter($front_matter, function ($key) use ($config) {
return in_array($key, $config['whitelist']);
}, ARRAY_FILTER_USE_KEY);
foreach ($config['merge'] as $key => $value) {
if (function_exists($value)) {
$value = call_user_func($value, $front_matter, $file->getFilename());
}
$refined[$key] = $value;
}
$contents = str_replace($document->getContent(), \Symfony\Component\Yaml\Yaml::dump($refined), $contents);
file_put_contents($file->getRealPath(), $contents);
}
function generate_date(array $front_matter, $filename)
{
if (isset($front_matter['date'])) {
return strtotime($front_matter['date']);
}
return strtotime(substr($filename, 0, 10));
}
function verify_categories(array $front_matter, $filename)
{
if (isset($front_matter['categories'])) {
return $front_matter['categories'];
}
return ['Main Thread'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment