Skip to content

Instantly share code, notes, and snippets.

@ariews
Created May 19, 2017 11:28
Show Gist options
  • Save ariews/1ff5e5b212853b6d2da6d12e12eb423c to your computer and use it in GitHub Desktop.
Save ariews/1ff5e5b212853b6d2da6d12e12eb423c to your computer and use it in GitHub Desktop.
<?php
/**
* Class MetaReplacer
*/
class MetaReplacer
{
/**
* Path to HEXO source
*
* @var string
*/
private $path = '/home/arie/hexo/source';
/**
* Only file with ext .rst in directory _drafts or _posts
*
* @var string
*/
private $pattern = '/^.+_(draft|post)s.+\.rst$/i';
/**
* Found files
*
* @var array
*/
private $files = [];
/**
* Initialize
*/
public function __construct()
{
$this->rstFinder();
}
/**
* Run replacer
*/
public function run()
{
foreach ($this->files as $file) {
$this->updateHeader($file);
}
}
/**
* Update file header
*
* @param string $file
*/
private function updateHeader($file)
{
$original_content = file_get_contents($file);
if (preg_match('!^(?<fl>-{2,})$\n(?<c>.*)\n^(?<sl>-{2,})$!sim', $original_content, $match)) {
$match = array_only($match, ['fl', 'c', 'sl']);
$separator = $match['fl'];
$original = join("\n", $match);
$this->createDescriptionFrom($match['c']);
$this->fixOverLineLength($match['c'], $separator);
$new_meta = join("\n", [$separator, $match['c'], $separator]);
$content = str_replace($original, $new_meta, $original_content);
file_put_contents($file, $content);
}
}
/**
* Create default description (copied from title)
*
* @param string $header
*/
private function createDescriptionFrom(& $header)
{
/*
* if only doesn't have description
*/
if (! preg_match('!^description:!mi', $header)) {
if (preg_match("!^(title: (?<title>.+))$!mi", $header, $match)) {
$header .= "\ndescription: {$match['title']}";
}
}
}
private function fixOverLineLength($content, & $overLine)
{
$array = explode("\n", $content);
/**
* Find max length
*
* @param $line
* @param $line_length
*/
$separator_check_length = function($line, & $line_length) {
$current_length = strlen($line);
if ($current_length > $line_length) {
$line_length = $current_length;
}
};
$length = 0;
foreach ($array as $line) $separator_check_length($line, $length);
$overLine = str_repeat('-', $length);
}
/**
* Find all .rst file
*/
private function rstFinder()
{
$directory = new \RecursiveDirectoryIterator($this->path);
$iterator = new \RecursiveIteratorIterator($directory);
$regex = new \RegexIterator($iterator, $this->pattern, \RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $r) $this->addFile($r[0]);
}
/**
* Add file to the list
*
* @param string $file
*/
private function addFile($file)
{
$this->files[$file];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment