AutoLoaderStructureTest: Allow PSR-4 directories to have files with 0 classes
[lhc/web/wiklou.git] / tests / phpunit / structure / AutoLoaderStructureTest.php
1 <?php
2
3 /**
4 * @coversNothing
5 */
6 class AutoLoaderStructureTest extends MediaWikiTestCase {
7 /**
8 * Assert that there were no classes loaded that are not registered with the AutoLoader.
9 *
10 * For example foo.php having class Foo and class Bar but only registering Foo.
11 * This is important because we should not be relying on Foo being used before Bar.
12 */
13 public function testAutoLoadConfig() {
14 $results = self::checkAutoLoadConf();
15
16 $this->assertEquals(
17 $results['expected'],
18 $results['actual']
19 );
20 }
21
22 public function providePSR4Completeness() {
23 foreach ( AutoLoader::$psr4Namespaces as $prefix => $dir ) {
24 foreach ( $this->recurseFiles( $dir ) as $file ) {
25 yield [ $prefix, $file ];
26 }
27 }
28 }
29
30 private function recurseFiles( $dir ) {
31 return ( new File_Iterator_Facade() )->getFilesAsArray( $dir, [ '.php' ] );
32 }
33
34 /**
35 * @dataProvider providePSR4Completeness
36 */
37 public function testPSR4Completeness( $prefix, $file ) {
38 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
39 $contents = file_get_contents( $file );
40 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
41 $classes = array_keys( $classesInFile );
42 if ( $classes ) {
43 $this->assertCount( 1, $classes,
44 "Only one class per file in PSR-4 autoloaded classes ($file)" );
45
46 $this->assertStringStartsWith( $prefix, $classes[0] );
47 $this->assertTrue(
48 class_exists( $classes[0] ) || interface_exists( $classes[0] ) || trait_exists( $classes[0] ),
49 "Class {$classes[0]} not autoloaded properly"
50 );
51 } else {
52 // Dummy assertion so this test isn't marked in risky
53 // if the file has no classes nor aliases in it
54 $this->assertCount( 0, $classes );
55 }
56
57 if ( $aliasesInFile ) {
58 $otherClasses = $wgAutoloadLocalClasses + $wgAutoloadClasses;
59 foreach ( $aliasesInFile as $alias => $class ) {
60 $this->assertArrayHasKey( $alias, $otherClasses,
61 'Alias must be in the classmap autoloader'
62 );
63 }
64 }
65 }
66
67 private static function parseFile( $contents ) {
68 // We could use token_get_all() here, but this is faster
69 // Note: Keep in sync with ClassCollector
70 $matches = [];
71 preg_match_all( '/
72 ^ [\t ]* (?:
73 (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
74 (?P<class> [a-zA-Z0-9_]+)
75 |
76 class_alias \s* \( \s*
77 ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
78 ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
79 \) \s* ;
80 |
81 class_alias \s* \( \s*
82 (?P<originalStatic> [a-zA-Z0-9_]+)::class \s* , \s*
83 ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
84 \) \s* ;
85 )
86 /imx', $contents, $matches, PREG_SET_ORDER );
87
88 $namespaceMatch = [];
89 preg_match( '/
90 ^ [\t ]*
91 namespace \s+
92 ([a-zA-Z0-9_]+(\\\\[a-zA-Z0-9_]+)*)
93 \s* ;
94 /imx', $contents, $namespaceMatch );
95 $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
96
97 $classesInFile = [];
98 $aliasesInFile = [];
99
100 foreach ( $matches as $match ) {
101 if ( !empty( $match['class'] ) ) {
102 // 'class Foo {}'
103 $class = $fileNamespace . $match['class'];
104 $classesInFile[$class] = true;
105 } else {
106 if ( !empty( $match['original'] ) ) {
107 // 'class_alias( "Foo", "Bar" );'
108 $aliasesInFile[$match['alias']] = $match['original'];
109 } else {
110 // 'class_alias( Foo::class, "Bar" );'
111 $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
112 }
113 }
114 }
115
116 return [ $classesInFile, $aliasesInFile ];
117 }
118
119 protected static function checkAutoLoadConf() {
120 global $wgAutoloadLocalClasses, $wgAutoloadClasses, $IP;
121
122 // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
123 $expected = $wgAutoloadLocalClasses + $wgAutoloadClasses;
124 $actual = [];
125
126 $files = array_unique( $expected );
127
128 foreach ( $files as $class => $file ) {
129 // Only prefix $IP if it doesn't have it already.
130 // Generally local classes don't have it, and those from extensions and test suites do.
131 if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
132 $filePath = "$IP/$file";
133 } else {
134 $filePath = $file;
135 }
136
137 if ( !file_exists( $filePath ) ) {
138 $actual[$class] = "[file '$filePath' does not exist]";
139 continue;
140 }
141
142 Wikimedia\suppressWarnings();
143 $contents = file_get_contents( $filePath );
144 Wikimedia\restoreWarnings();
145
146 if ( $contents === false ) {
147 $actual[$class] = "[couldn't read file '$filePath']";
148 continue;
149 }
150
151 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
152
153 foreach ( $classesInFile as $className => $ignore ) {
154 $actual[$className] = $file;
155 }
156
157 // Only accept aliases for classes in the same file, because for correct
158 // behavior, all aliases for a class must be set up when the class is loaded
159 // (see <https://bugs.php.net/bug.php?id=61422>).
160 foreach ( $aliasesInFile as $alias => $class ) {
161 if ( isset( $classesInFile[$class] ) ) {
162 $actual[$alias] = $file;
163 } else {
164 $actual[$alias] = "[original class not in $file]";
165 }
166 }
167 }
168
169 return [
170 'expected' => $expected,
171 'actual' => $actual,
172 ];
173 }
174
175 public function testAutoloadOrder() {
176 $path = realpath( __DIR__ . '/../../..' );
177 $oldAutoload = file_get_contents( $path . '/autoload.php' );
178 $generator = new AutoloadGenerator( $path, 'local' );
179 $generator->setExcludePaths( array_values( AutoLoader::getAutoloadNamespaces() ) );
180 $generator->initMediaWikiDefault();
181 $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
182
183 $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
184 ' output of generateLocalAutoload.php script.' );
185 }
186 }