Normalize dir path in AutoLoaderStructureTest
[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, $dir, $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, $dir, $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(
44 1,
45 $classes,
46 "Only one class per file in PSR-4 autoloaded classes ($file)"
47 );
48
49 // Check that the expected class name (based on the filename) is the
50 // same as the one we found.
51 // Strip directory prefix from front of filename, and .php extension
52 $dirNameLength = strlen( realpath( $dir ) ) + 1; // +1 for the trailing slash
53 $fileBaseName = substr( $file, $dirNameLength );
54 $abbrFileName = substr( $fileBaseName, 0, -4 );
55 $expectedClassName = $prefix . str_replace( '/', '\\', $abbrFileName );
56
57 $this->assertSame(
58 $expectedClassName,
59 $classes[0],
60 "Class not autoloaded properly"
61 );
62
63 } else {
64 // Dummy assertion so this test isn't marked in risky
65 // if the file has no classes nor aliases in it
66 $this->assertCount( 0, $classes );
67 }
68
69 if ( $aliasesInFile ) {
70 $otherClasses = $wgAutoloadLocalClasses + $wgAutoloadClasses;
71 foreach ( $aliasesInFile as $alias => $class ) {
72 $this->assertArrayHasKey( $alias, $otherClasses,
73 'Alias must be in the classmap autoloader'
74 );
75 }
76 }
77 }
78
79 private static function parseFile( $contents ) {
80 // We could use token_get_all() here, but this is faster
81 // Note: Keep in sync with ClassCollector
82 $matches = [];
83 preg_match_all( '/
84 ^ [\t ]* (?:
85 (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
86 (?P<class> \w+)
87 |
88 class_alias \s* \( \s*
89 ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
90 ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
91 \) \s* ;
92 |
93 class_alias \s* \( \s*
94 (?P<originalStatic> [\w\\\\]+)::class \s* , \s*
95 ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
96 \) \s* ;
97 )
98 /imx', $contents, $matches, PREG_SET_ORDER );
99
100 $namespaceMatch = [];
101 preg_match( '/
102 ^ [\t ]*
103 namespace \s+
104 (\w+(\\\\\w+)*)
105 \s* ;
106 /imx', $contents, $namespaceMatch );
107 $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
108
109 $classesInFile = [];
110 $aliasesInFile = [];
111
112 foreach ( $matches as $match ) {
113 if ( !empty( $match['class'] ) ) {
114 // 'class Foo {}'
115 $class = $fileNamespace . $match['class'];
116 $classesInFile[$class] = true;
117 } elseif ( !empty( $match['original'] ) ) {
118 // 'class_alias( "Foo", "Bar" );'
119 $aliasesInFile[$match['alias']] = $match['original'];
120 } else {
121 // 'class_alias( Foo::class, "Bar" );'
122 $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
123 }
124 }
125
126 return [ $classesInFile, $aliasesInFile ];
127 }
128
129 protected static function checkAutoLoadConf() {
130 global $wgAutoloadLocalClasses, $wgAutoloadClasses, $IP;
131
132 // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
133 $expected = $wgAutoloadLocalClasses + $wgAutoloadClasses;
134 $actual = [];
135
136 $psr4Namespaces = [];
137 foreach ( AutoLoader::getAutoloadNamespaces() as $ns => $path ) {
138 $psr4Namespaces[rtrim( $ns, '\\' ) . '\\'] = rtrim( $path, '/' );
139 }
140
141 foreach ( $expected as $class => $file ) {
142 // Only prefix $IP if it doesn't have it already.
143 // Generally local classes don't have it, and those from extensions and test suites do.
144 if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
145 $filePath = "$IP/$file";
146 } else {
147 $filePath = $file;
148 }
149
150 if ( !file_exists( $filePath ) ) {
151 $actual[$class] = "[file '$filePath' does not exist]";
152 continue;
153 }
154
155 Wikimedia\suppressWarnings();
156 $contents = file_get_contents( $filePath );
157 Wikimedia\restoreWarnings();
158
159 if ( $contents === false ) {
160 $actual[$class] = "[couldn't read file '$filePath']";
161 continue;
162 }
163
164 list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
165
166 foreach ( $classesInFile as $className => $ignore ) {
167 // Skip if it's a PSR4 class
168 $parts = explode( '\\', $className );
169 for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
170 $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
171 if ( isset( $psr4Namespaces[$ns] ) ) {
172 $expectedPath = $psr4Namespaces[$ns] . '/'
173 . implode( '/', array_slice( $parts, $i ) )
174 . '.php';
175 if ( $filePath === $expectedPath ) {
176 continue 2;
177 }
178 }
179 }
180
181 // Nope, add it.
182 $actual[$className] = $file;
183 }
184
185 // Only accept aliases for classes in the same file, because for correct
186 // behavior, all aliases for a class must be set up when the class is loaded
187 // (see <https://bugs.php.net/bug.php?id=61422>).
188 foreach ( $aliasesInFile as $alias => $class ) {
189 if ( isset( $classesInFile[$class] ) ) {
190 $actual[$alias] = $file;
191 } else {
192 $actual[$alias] = "[original class not in $file]";
193 }
194 }
195 }
196
197 return [
198 'expected' => $expected,
199 'actual' => $actual,
200 ];
201 }
202
203 public function testAutoloadOrder() {
204 $path = realpath( __DIR__ . '/../../..' );
205 $oldAutoload = file_get_contents( $path . '/autoload.php' );
206 $generator = new AutoloadGenerator( $path, 'local' );
207 $generator->setPsr4Namespaces( AutoLoader::getAutoloadNamespaces() );
208 $generator->initMediaWikiDefault();
209 $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
210
211 $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
212 ' output of generateLocalAutoload.php script.' );
213 }
214 }