CodeTestAbstract.php 2.1 KB

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