| 1 |
<?php |
| 2 |
|
| 3 |
namespace PhpParser; |
| 4 |
|
| 5 |
abstract class CodeTestAbstract extends \PHPUnit_Framework_TestCase |
| 6 |
{ |
| 7 |
protected function getTests($directory, $fileExtension) { |
| 8 |
$directory = realpath($directory); |
| 9 |
$it = new \RecursiveDirectoryIterator($directory); |
| 10 |
$it = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::LEAVES_ONLY); |
| 11 |
$it = new \RegexIterator($it, '(\.' . preg_quote($fileExtension) . '$)'); |
| 12 |
|
| 13 |
$tests = array(); |
| 14 |
foreach ($it as $file) { |
| 15 |
$fileName = $file->getPathname(); |
| 16 |
$fileContents = file_get_contents($fileName); |
| 17 |
$fileContents = canonicalize($fileContents); |
| 18 |
|
| 19 |
// evaluate @@{expr}@@ expressions |
| 20 |
$fileContents = preg_replace_callback( |
| 21 |
'/@@\{(.*?)\}@@/', |
| 22 |
function($matches) { |
| 23 |
return eval('return ' . $matches[1] . ';'); |
| 24 |
}, |
| 25 |
$fileContents |
| 26 |
); |
| 27 |
|
| 28 |
// parse sections |
| 29 |
$parts = preg_split("/\n-----(?:\n|$)/", $fileContents); |
| 30 |
|
| 31 |
// first part is the name |
| 32 |
$name = array_shift($parts) . ' (' . $fileName . ')'; |
| 33 |
$shortName = ltrim(str_replace($directory, '', $fileName), '/\\'); |
| 34 |
|
| 35 |
// multiple sections possible with always two forming a pair |
| 36 |
$chunks = array_chunk($parts, 2); |
| 37 |
foreach ($chunks as $i => $chunk) { |
| 38 |
$dataSetName = $shortName . (count($chunks) > 1 ? '#' . $i : ''); |
| 39 |
list($expected, $mode) = $this->extractMode($chunk[1]); |
| 40 |
$tests[$dataSetName] = array($name, $chunk[0], $expected, $mode); |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
return $tests; |
| 45 |
} |
| 46 |
|
| 47 |
private function extractMode($expected) { |
| 48 |
$firstNewLine = strpos($expected, "\n"); |
| 49 |
if (false === $firstNewLine) { |
| 50 |
$firstNewLine = strlen($expected); |
| 51 |
} |
| 52 |
|
| 53 |
$firstLine = substr($expected, 0, $firstNewLine); |
| 54 |
if (0 !== strpos($firstLine, '!!')) { |
| 55 |
return [$expected, null]; |
| 56 |
} |
| 57 |
|
| 58 |
$expected = (string) substr($expected, $firstNewLine + 1); |
| 59 |
return [$expected, substr($firstLine, 2)]; |
| 60 |
} |
| 61 |
} |
| 62 |
|