d534bc7e2f00380407527567393a46b86644fac0
[civicrm-core.git] / Civi / CiUtil / PHPUnitScanner.php
1 <?php
2 namespace Civi\CiUtil;
3
4 use Symfony\Component\Finder\Finder;
5
6 /**
7 * Search for PHPUnit test cases
8 */
9 class PHPUnitScanner {
10 /**
11 * @return array<string> class names
12 */
13 public static function _findTestClasses($path) {
14 // print_r(array(
15 // 'loading' => $path,
16 // get_included_files()
17 // ));
18
19 $origClasses = get_declared_classes();
20 require_once $path;
21 $newClasses = get_declared_classes();
22
23 return preg_grep('/Test$/', array_diff(
24 $newClasses,
25 $origClasses
26 ));
27 }
28
29 /**
30 * @return array
31 * (string $file => string $class)
32 */
33 public static function findTestClasses($paths) {
34 $testClasses = array();
35 $finder = new Finder();
36
37 foreach ($paths as $path) {
38 if (is_dir($path)) {
39 foreach ($finder->files()->in($paths)->name('*Test.php') as $file) {
40 $testClass = self::_findTestClasses((string) $file);
41 if (count($testClass) == 1) {
42 $testClasses[(string) $file] = array_shift($testClass);
43 }
44 elseif (count($testClass) > 1) {
45 throw new \Exception("Too many classes in $file");
46 }
47 else {
48 throw new \Exception("Too few classes in $file");
49 }
50 }
51 }
52 elseif (is_file($path)) {
53 $testClass = self::_findTestClasses($path);
54 if (count($testClass) == 1) {
55 $testClasses[$path] = array_shift($testClass);
56 }
57 elseif (count($testClass) > 1) {
58 throw new \Exception("Too many classes in $path");
59 }
60 else {
61 throw new \Exception("Too few classes in $path");
62 }
63 }
64 }
65
66 return $testClasses;
67 }
68
69 /**
70 * @param array $paths
71 *
72 * @return array
73 * each element is an array with keys:
74 * - file: string
75 * - class: string
76 * - method: string
77 */
78 public static function findTestsByPath($paths) {
79 $r = array();
80 $testClasses = self::findTestClasses($paths);
81 foreach ($testClasses as $testFile => $testClass) {
82 $clazz = new \ReflectionClass($testClass);
83 foreach ($clazz->getMethods() as $method) {
84 if (preg_match('/^test/', $method->name)) {
85 $r[] = array(
86 'file' => $testFile,
87 'class' => $testClass,
88 'method' => $method->name
89 );
90 }
91 }
92 }
93 return $r;
94 }
95 }