Merge pull request #16931 from civicrm/5.24
[civicrm-core.git] / Civi / CiUtil / PHPUnitScanner.php
CommitLineData
f03dc6b0
TO
1<?php
2namespace Civi\CiUtil;
46bcf597 3
f03dc6b0
TO
4use Symfony\Component\Finder\Finder;
5
6/**
7 * Search for PHPUnit test cases
8 */
9class PHPUnitScanner {
34f3bbd9 10
f03dc6b0 11 /**
257e7666
EM
12 * @param $path
13 * @return array <string> class names
f03dc6b0 14 */
00be9182 15 public static function _findTestClasses($path) {
bed98343 16 // print_r(array(
17 // 'loading' => $path,
18 // get_included_files()
19 // ));
f03dc6b0
TO
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 /**
257e7666
EM
31 * @param $paths
32 * @return array (string $file => string $class)
257e7666 33 * @throws \Exception
f03dc6b0 34 */
00be9182 35 public static function findTestClasses($paths) {
c64f69d9 36 $testClasses = [];
f03dc6b0
TO
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 /**
16b10e64
CW
72 * @param array $paths
73 *
a6c01b45
CW
74 * @return array
75 * each element is an array with keys:
f03dc6b0
TO
76 * - file: string
77 * - class: string
78 * - method: string
79 */
00be9182 80 public static function findTestsByPath($paths) {
c64f69d9 81 $r = [];
f03dc6b0
TO
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)) {
c64f69d9 87 $r[] = [
f03dc6b0
TO
88 'file' => $testFile,
89 'class' => $testClass,
bed98343 90 'method' => $method->name,
c64f69d9 91 ];
f03dc6b0
TO
92 }
93 }
94 }
95 return $r;
96 }
96025800 97
c206647d 98}