-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdocs-extract-php-code
More file actions
executable file
·64 lines (49 loc) · 1.85 KB
/
Copy pathdocs-extract-php-code
File metadata and controls
executable file
·64 lines (49 loc) · 1.85 KB
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
#!/usr/bin/env php
<?php
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface;
use League\CommonMark\Extension\FrontMatter\FrontMatterExtension;
use League\CommonMark\Node\Query;
use League\CommonMark\Parser\MarkdownParser;
use Wnx\CommonmarkMarkdownRenderer\MarkdownRendererExtension;
require __DIR__ . '/../vendor/autoload.php';
$environment = new Environment([]);
$environment->addExtension(new MarkdownRendererExtension());
$environment->addExtension(new FrontMatterExtension(
// keep the raw YAML string so it round-trips byte-identically
new class implements FrontMatterDataParserInterface {
public function parse(string $frontMatter): string
{
return $frontMatter;
}
},
));
$parser = new MarkdownParser($environment);
$targetDir = __DIR__ . '/../docs_php';
if (file_exists($targetDir)) {
exec('rm -rf ' . $targetDir);
}
mkdir($targetDir);
$finder = new Symfony\Component\Finder\Finder();
$finder->files()->in(__DIR__ . '/../docs')->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') {
continue;
}
$source = sprintf('%s:%s', $file->getRealPath(), $node->getStartLine());
$code = "<?php\n// " . $source . "\n\n" . $node->getLiteral();
$targetPath = $targetDir . '/' . $fileName . '_' . $i . '.php';
file_put_contents($targetPath, $code);
}
}