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