-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadme.php
53 lines (44 loc) · 1.56 KB
/
readme.php
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
<?php
include 'vendor/autoload.php';
/** Parses the content of markdown and extract the code blocks, optional of
* specific language. */
function parse(string $markdown, string $lang=null): Generator {
preg_match_all("/(.*)\n(.+)\n\n```$lang([^`]*)```/", $markdown, $matches);
foreach ($matches[3] as $i => $code) {
yield trim(ltrim($matches[1][$i], '*') . ' ' . rtrim($matches[2][$i], ':')) => $code;
}
}
/** Creates a PHP code run environment. */
function runtime(string $init): callable {
static $cmd = 'php -dzend.assertions=1 -dassert.active=1 -dassert.quiet_eval=0 -dassert.bail=1 -dassert.warning=1';
$init = "include 'vendor/autoload.php';\n\n$init";
return function(string $code) use($cmd, $init): string {
$cmd .= ' -r ' . escapeshellarg($init . $code);
$out = system($cmd, $ret);
if ($ret !== 0) {
throw new RuntimeException($out, $ret);
}
return $out;
};
}
/** Parse and run a markdown file. */
function main(string $filename) {
$tests = iterator_to_array(parse(file_get_contents($filename), 'php'));
$init = array_shift($tests);
$exec = runtime($init);
$ret = 0;
foreach ($tests as $id => $test) {
try {
$out = $exec($test);
fwrite(STDOUT, "👍 $id\n");
if (!empty($out)) {
fwrite(STDOUT, "🐞 $out\n\n");
}
} catch (RuntimeException $ex) {
fwrite(STDERR, "🔴 $id\n{$ex}\n\n");
$ret = 1;
}
}
return $ret;
}
exit(main($argv[1] ?? 'README.md'));