|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the league/commonmark package. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code. |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace League\CommonMark\Util; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Reads in a CommonMark spec document and extracts the input/output examples for testing against them |
|
18
|
|
|
*/ |
|
19
|
|
|
final class SpecReader |
|
20
|
|
|
{ |
|
21
|
|
|
private function __construct() |
|
22
|
|
|
{ |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> |
|
27
|
|
|
*/ |
|
28
|
|
|
public static function read(string $data): iterable |
|
29
|
|
|
{ |
|
30
|
|
|
// Normalize newlines for platform independence |
|
31
|
|
|
$data = \preg_replace('/\r\n?/', "\n", $data); |
|
32
|
|
|
\assert($data !== null); |
|
33
|
|
|
$data = \preg_replace('/<!-- END TESTS -->.*$/', '', $data); |
|
34
|
|
|
\assert($data !== null); |
|
35
|
|
|
\preg_match_all('/^`{32} (example ?\w*)\n([\s\S]*?)^\.\n([\s\S]*?)^`{32}$|^#{1,6} *(.*)$/m', $data, $matches, PREG_SET_ORDER); |
|
36
|
|
|
|
|
37
|
|
|
$currentSection = 'Example'; |
|
38
|
|
|
$exampleNumber = 0; |
|
39
|
|
|
|
|
40
|
|
|
foreach ($matches as $match) { |
|
41
|
|
|
if (isset($match[4])) { |
|
42
|
|
|
$currentSection = $match[4]; |
|
43
|
|
|
continue; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
yield \trim($currentSection . ' #' . $exampleNumber) => [ |
|
47
|
|
|
'input' => \str_replace('→', "\t", $match[2]), |
|
48
|
|
|
'output' => \str_replace('→', "\t", $match[3]), |
|
49
|
|
|
'type' => $match[1], |
|
50
|
|
|
'section' => $currentSection, |
|
51
|
|
|
'number' => $exampleNumber++, |
|
52
|
|
|
]; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @return iterable<string, array{input: string, output: string, type: string, section: string, number: int}> |
|
58
|
|
|
*/ |
|
59
|
|
|
public static function readFile(string $filename): iterable |
|
60
|
|
|
{ |
|
61
|
|
|
if (($data = \file_get_contents($filename)) === false) { |
|
62
|
|
|
throw new \RuntimeException(\sprintf('Failed to load spec from %s', $filename)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return self::read($data); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|