-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocs-inject-php-code
executable file
·70 lines (50 loc) · 1.84 KB
/
docs-inject-php-code
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env php
<?php
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Node\Query;
use League\CommonMark\Parser\MarkdownParser;
use Wnx\CommonmarkMarkdownRenderer\MarkdownRendererExtension;
use Wnx\CommonmarkMarkdownRenderer\Renderer\MarkdownRenderer;
require __DIR__ . '/../vendor/autoload.php';
$environment = new Environment([]);
$environment->addExtension(new MarkdownRendererExtension());
$parser = new MarkdownParser($environment);
$markdownRenderer = new MarkdownRenderer($environment);
$targetDir = __DIR__ . '/../docs_php';
if (!file_exists($targetDir)) {
exit(1);
}
$finder = new Symfony\Component\Finder\Finder();
$finder->files()->in(__DIR__ . '/../docs/pages')->name('*.md');
foreach ($finder as $file) {
$fileName = pathinfo($file->getBasename(), PATHINFO_FILENAME);
$content = file_get_contents($file->getPathname());
$document = $parser->parse($content);
$result = (new Query())
->where(Query::type(FencedCode::class))
->findAll($document);
/**
* @var FencedCode $node
*/
foreach ($result as $i => $node) {
if ($node->getInfo() !== 'php') {
$node->setLiteral(trim($node->getLiteral()));
continue;
}
$targetPath = $targetDir . '/' . $fileName . '_' . $i . '.php';
if (!file_exists($targetPath)) {
$node->setLiteral(trim($node->getLiteral()));
continue;
}
$code = file_get_contents($targetPath);
$lines = explode("\n", $code);
array_splice($lines, 0, 2);
$code = implode("\n", $lines);
$node->setLiteral(trim($code));
}
file_put_contents($file->getPathname(), $markdownRenderer->renderDocument($document));
}
if (file_exists($targetDir)) {
exec('rm -rf ' . $targetDir);
}