AutoLoaderStructureTest.php 5.7 KB

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