CodeTestAbstract.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace PhpParser;
  3. abstract class CodeTestAbstract extends \PHPUnit_Framework_TestCase
  4. {
  5. protected function getTests($directory, $fileExtension) {
  6. $it = new \RecursiveDirectoryIterator($directory);
  7. $it = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::LEAVES_ONLY);
  8. $it = new \RegexIterator($it, '(\.' . preg_quote($fileExtension) . '$)');
  9. $tests = array();
  10. foreach ($it as $file) {
  11. $fileName = realpath($file->getPathname());
  12. $fileContents = file_get_contents($fileName);
  13. // evaluate @@{expr}@@ expressions
  14. $fileContents = preg_replace_callback(
  15. '/@@\{(.*?)\}@@/',
  16. array($this, 'evalCallback'),
  17. $fileContents
  18. );
  19. // parse sections
  20. $parts = array_map('trim', explode('-----', $fileContents));
  21. // first part is the name
  22. $name = array_shift($parts) . ' (' . $fileName . ')';
  23. // multiple sections possible with always two forming a pair
  24. foreach (array_chunk($parts, 2) as $chunk) {
  25. $tests[] = array($name, $chunk[0], $chunk[1]);
  26. }
  27. }
  28. return $tests;
  29. }
  30. protected function evalCallback($matches) {
  31. return eval('return ' . $matches[1] . ';');
  32. }
  33. protected function canonicalize($str) {
  34. // trim from both sides
  35. $str = trim($str);
  36. // normalize EOL to \n
  37. $str = str_replace(array("\r\n", "\r"), "\n", $str);
  38. // trim right side of all lines
  39. return implode("\n", array_map('rtrim', explode("\n", $str)));
  40. }
  41. }