Split AutoloaderTest into a structure and class test
[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 $this->assertCount( 1, $classes,
43 "Only one class per file in PSR-4 autoloaded classes ($file)" );
44
45 $this->assertStringStartsWith( $prefix, $classes[0] );
46 $this->assertTrue(
47 class_exists( $classes[0] ) || interface_exists( $classes[0] ) || trait_exists( $classes[0] ),
48 "Class {$classes[0]} not autoloaded properly"
49 );
50
51 $otherClasses = $wgAutoloadLocalClasses + $wgAutoloadClasses;
52 foreach ( $aliasesInFile as $alias => $class ) {
53 $this->assertArrayHasKey( $alias, $otherClasses,
54 'Alias must be in the classmap autoloader'
55 );
56 }
57 }
58
59 private static function parseFile( $contents ) {
60 // We could use token_get_all() here, but this is faster
61 // Note: Keep in sync with ClassCollector
62 $matches = [];
63 preg_match_all( '/
64 ^ [\t ]* (?:
65 (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
66 (?P<class> [a-zA-Z0-9_]+)
67 |
68 class_alias \s* \( \s*
69 ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
70 ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
71 \) \s* ;
72 |
73 class_alias \s* \( \s*
74 (?P<originalStatic> [a-zA-Z0-9_]+)::class \s* , \s*
75 ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
76 \) \s* ;
77 )
78 /imx', $contents, $matches, PREG_SET_ORDER );
79
80 $namespaceMatch = [];
81 preg_match( '/
82 ^ [\t ]*
83 namespace \s+
84 ([a-zA-Z0-9_]+(\\\\[a-zA-Z0-9_]+)*)
85 \s* ;
86 /imx', $contents, $namespaceMatch );
87 $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
88
89 $classesInFile = [];
90 $aliasesInFile = [];
91
92 foreach ( $matches as $match ) {
93 if ( !empty( $match['class'] ) ) {
94 // 'class Foo {}'
95 $class = $fileNamespace . $match['class'];
96 $classesInFile[$class] = true;
97 } else {
98 if ( !empty( $match['original'] ) ) {
99 // 'class_alias( "Foo", "Bar" );'
100 $aliasesInFile[$match['alias']] = $match['original'];
101 } else {
102 // 'class_alias( Foo::class, "Bar" );'
103 $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
104 }
105 }
106 }
107
108 return [ $classesInFile, $aliasesInFile ];
109 }
110
111 protected static function checkAutoLoadConf() {
112 global $wgAutoloadLocalClasses, $wgAutoloadClasses, $IP;
113
114 // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
115 $expected = $wgAutoloadLocalClasses + $wgAutoloadClasses;
116 $actual = [];
117
118 $files = array_unique( $expected );
119
120 foreach ( $files as $class => $file ) {
121 // Only prefix $IP if it doesn't have it already.
122 // Generally local classes don't have it, and those from extensions and test suites do.
123 if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
124 $filePath = "$IP/$file";
125 } else {
126 $filePath = $file;
127 }
128
129 if ( !file_exists( $filePath ) ) {
130 $actual[$class] = "[file '$filePath' does not exist]";
131 continue;
132 }
133
134 Wikimedia\suppressWarnings();
135 $contents = file_get_contents( $filePath );
136 Wikimedia\restoreWarnings();
137
138 if ( $contents === false ) {
139 $actual[$class] = "[couldn't read file '$filePath']";
140 continue;
141 }
142
143 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
144
145 foreach ( $classesInFile as $className => $ignore ) {
146 $actual[$className] = $file;
147 }
148
149 // Only accept aliases for classes in the same file, because for correct
150 // behavior, all aliases for a class must be set up when the class is loaded
151 // (see <https://bugs.php.net/bug.php?id=61422>).
152 foreach ( $aliasesInFile as $alias => $class ) {
153 if ( isset( $classesInFile[$class] ) ) {
154 $actual[$alias] = $file;
155 } else {
156 $actual[$alias] = "[original class not in $file]";
157 }
158 }
159 }
160
161 return [
162 'expected' => $expected,
163 'actual' => $actual,
164 ];
165 }
166
167 public function testAutoloadOrder() {
168 $path = realpath( __DIR__ . '/../../..' );
169 $oldAutoload = file_get_contents( $path . '/autoload.php' );
170 $generator = new AutoloadGenerator( $path, 'local' );
171 $generator->setExcludePaths( array_values( AutoLoader::getAutoloadNamespaces() ) );
172 $generator->initMediaWikiDefault();
173 $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
174
175 $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
176 ' output of generateLocalAutoload.php script.' );
177 }
178 }