f63dc926536d1405564f9d87fc3cc3c6ca87aea3
[yaffs-website] / vendor / nikic / php-parser / test / PhpParser / CodeTestParser.php
1 <?php declare(strict_types=1);
2
3 namespace PhpParser;
4
5 class CodeTestParser
6 {
7     public function parseTest($code, $chunksPerTest) {
8         $code = canonicalize($code);
9
10         // evaluate @@{expr}@@ expressions
11         $code = preg_replace_callback(
12             '/@@\{(.*?)\}@@/',
13             function($matches) {
14                 return eval('return ' . $matches[1] . ';');
15             },
16             $code
17         );
18
19         // parse sections
20         $parts = preg_split("/\n-----(?:\n|$)/", $code);
21
22         // first part is the name
23         $name = array_shift($parts);
24
25         // multiple sections possible with always two forming a pair
26         $chunks = array_chunk($parts, $chunksPerTest);
27         $tests = [];
28         foreach ($chunks as $i => $chunk) {
29             $lastPart = array_pop($chunk);
30             list($lastPart, $mode) = $this->extractMode($lastPart);
31             $tests[] = [$mode, array_merge($chunk, [$lastPart])];
32         }
33
34         return [$name, $tests];
35     }
36
37     public function reconstructTest($name, array $tests) {
38         $result = $name;
39         foreach ($tests as list($mode, $parts)) {
40             $lastPart = array_pop($parts);
41             foreach ($parts as $part) {
42                 $result .= "\n-----\n$part";
43             }
44
45             $result .= "\n-----\n";
46             if (null !== $mode) {
47                 $result .= "!!$mode\n";
48             }
49             $result .= $lastPart;
50         }
51         return $result;
52     }
53
54     private function extractMode($expected) {
55         $firstNewLine = strpos($expected, "\n");
56         if (false === $firstNewLine) {
57             $firstNewLine = strlen($expected);
58         }
59
60         $firstLine = substr($expected, 0, $firstNewLine);
61         if (0 !== strpos($firstLine, '!!')) {
62             return [$expected, null];
63         }
64
65         $expected = (string) substr($expected, $firstNewLine + 1);
66         return [$expected, substr($firstLine, 2)];
67     }
68 }