Merge pull request #4875 from civicrm/minor-fix
[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 {
10 /**
11 * @return array<string> class names
12 */
00be9182 13 public static function _findTestClasses($path) {
f03dc6b0
TO
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 /**
a6c01b45
CW
30 * @return array
31 * (string $file => string $class)
f03dc6b0 32 */
00be9182 33 public static function findTestClasses($paths) {
f03dc6b0
TO
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 $testClasses
a6c01b45
CW
71 * @return array
72 * each element is an array with keys:
f03dc6b0
TO
73 * - file: string
74 * - class: string
75 * - method: string
76 */
00be9182 77 public static function findTestsByPath($paths) {
f03dc6b0
TO
78 $r = array();
79 $testClasses = self::findTestClasses($paths);
80 foreach ($testClasses as $testFile => $testClass) {
81 $clazz = new \ReflectionClass($testClass);
82 foreach ($clazz->getMethods() as $method) {
83 if (preg_match('/^test/', $method->name)) {
84 $r[] = array(
85 'file' => $testFile,
86 'class' => $testClass,
87 'method' => $method->name
88 );
89 }
90 }
91 }
92 return $r;
93 }
c206647d 94}