1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';
// Extract snippets from readme.
$readme = file(__DIR__ . '/../README.md', FILE_SKIP_EMPTY_LINES + FILE_IGNORE_NEW_LINES);
if ($readme === false) {
throw new RuntimeException("Failed to open readme file");
}
passthru('rm -r ' . __DIR__ . '/snippets');
mkdir(__DIR__ . '/snippets');
/**
* @param string[] $lines
* @return string[]
*/
function readSnippet(&$lines): array
{
$snippet = [];
while ($lines[0] !== '```') {
$snippet[] = array_shift($lines);
}
array_shift($lines);
return $snippet;
}
/**
* @param string[] $snippet
* @param string $name
* @return void
*/
function storeSnippet(array $snippet, string $name)
{
// We replace occurrences of __DIR__
$fileName = __DIR__ . '/snippets/' . strtr($name, [' ' => '-', '/' => '_or_']) . '.php';
file_put_contents($fileName, strtr(implode("\n", ["<?php", ...$snippet]), [
'__DIR__' => '__DIR__ . "/.."'
]));
}
$title = 'Root';
while ($readme !== []) {
$line = array_shift($readme);
if (preg_match('~^\#+\s+(.*)$~', $line, $matches) === 1) {
$title = $matches[1];
}
if ($line === '```php') {
$snippet = readSnippet($readme);
storeSnippet($snippet, $title);
}
}
|