Skip to content

Commit 3c096b1

Browse files
authored
code_samples_usage.php: Handle --8<-- syntax (#2578)
1 parent 14fba98 commit 3c096b1

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

tools/code_samples/code_samples_usage.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@ function getBlockContents(array $block): array
133133
$rawBlockCodeLines = [];
134134
$oneBasedBlockCodeLines = [];
135135
$includedFilesLines = [];
136-
foreach ($block as $blockSourceLine) {
136+
$skip = false;
137+
foreach ($block as $blockSourceLineIndex => $blockSourceLine) {
137138
if (preg_match('@```.* hl_lines="([^"]+)"@', $blockSourceLine, $matches)) {
138139
$rawHighlightedLines = explode(' ', $matches[1]);
139140
foreach ($rawHighlightedLines as $rawHighlightedLine) {
@@ -171,7 +172,17 @@ function getBlockContents(array $block): array
171172
$solvedLine = str_replace($matchString, implode(PHP_EOL . $matches['glue'][$matchIndex], $sample) . PHP_EOL, $solvedLine);
172173
}
173174
$rawBlockCodeLines = array_merge($rawBlockCodeLines, explode(PHP_EOL, $solvedLine));
174-
} elseif (!str_contains($blockSourceLine, '```')) {
175+
} elseif (str_contains($blockSourceLine, '--8<--')) {
176+
if (!$skip) {
177+
$includedFilePath = trim($block[$blockSourceLineIndex+1]);
178+
$includedFilesLines[$includedFilePath] = file($includedFilePath, FILE_IGNORE_NEW_LINES);
179+
if (!is_array($includedFilesLines[$includedFilePath])) {
180+
throw new RuntimeException("The following included file can't be opened: $includedFilePath");
181+
}
182+
$rawBlockCodeLines = array_merge($rawBlockCodeLines, $includedFilesLines[$includedFilePath]);
183+
}
184+
$skip = !$skip;
185+
} elseif (!str_contains($blockSourceLine, '```') && !$skip) {
175186
$rawBlockCodeLines[] = $blockSourceLine;
176187
}
177188
}

0 commit comments

Comments
 (0)