Created
January 4, 2019 18:24
-
-
Save jasonmccreary/af977128c87cb8404515f103e3141d7f to your computer and use it in GitHub Desktop.
Script to condense Jekyll front matter for Jigsaw
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 | |
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