MediaWiki  1.32.5
AutoLoaderStructureTest.php
Go to the documentation of this file.
1 <?php
2 
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 
37  public function testPSR4Completeness( $prefix, $dir, $file ) {
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  // Check that the expected class name (based on the filename) is the
47  // same as the one we found.
48  // Strip directory prefix from front of filename, and .php extension
49  $abbrFileName = substr( substr( $file, strlen( $dir ) ), 0, -4 );
50  $expectedClassName = $prefix . str_replace( '/', '\\', $abbrFileName );
51 
52  $this->assertSame(
53  $expectedClassName,
54  $classes[0],
55  "Class not autoloaded properly"
56  );
57 
58  } else {
59  // Dummy assertion so this test isn't marked in risky
60  // if the file has no classes nor aliases in it
61  $this->assertCount( 0, $classes );
62  }
63 
64  if ( $aliasesInFile ) {
66  foreach ( $aliasesInFile as $alias => $class ) {
67  $this->assertArrayHasKey( $alias, $otherClasses,
68  'Alias must be in the classmap autoloader'
69  );
70  }
71  }
72  }
73 
74  private static function parseFile( $contents ) {
75  // We could use token_get_all() here, but this is faster
76  // Note: Keep in sync with ClassCollector
77  $matches = [];
78  preg_match_all( '/
79  ^ [\t ]* (?:
80  (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
81  (?P<class> [a-zA-Z0-9_]+)
82  |
83  class_alias \s* \( \s*
84  ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
85  ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
86  \) \s* ;
87  |
88  class_alias \s* \( \s*
89  (?P<originalStatic> [a-zA-Z0-9_]+)::class \s* , \s*
90  ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
91  \) \s* ;
92  )
93  /imx', $contents, $matches, PREG_SET_ORDER );
94 
95  $namespaceMatch = [];
96  preg_match( '/
97  ^ [\t ]*
98  namespace \s+
99  ([a-zA-Z0-9_]+(\\\\[a-zA-Z0-9_]+)*)
100  \s* ;
101  /imx', $contents, $namespaceMatch );
102  $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
103 
104  $classesInFile = [];
105  $aliasesInFile = [];
106 
107  foreach ( $matches as $match ) {
108  if ( !empty( $match['class'] ) ) {
109  // 'class Foo {}'
110  $class = $fileNamespace . $match['class'];
111  $classesInFile[$class] = true;
112  } else {
113  if ( !empty( $match['original'] ) ) {
114  // 'class_alias( "Foo", "Bar" );'
115  $aliasesInFile[$match['alias']] = $match['original'];
116  } else {
117  // 'class_alias( Foo::class, "Bar" );'
118  $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
119  }
120  }
121  }
122 
123  return [ $classesInFile, $aliasesInFile ];
124  }
125 
126  protected static function checkAutoLoadConf() {
128 
129  // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
131  $actual = [];
132 
133  $psr4Namespaces = [];
134  foreach ( AutoLoader::getAutoloadNamespaces() as $ns => $path ) {
135  $psr4Namespaces[rtrim( $ns, '\\' ) . '\\'] = rtrim( $path, '/' );
136  }
137 
138  $files = array_unique( $expected );
139 
140  foreach ( $files as $class => $file ) {
141  // Only prefix $IP if it doesn't have it already.
142  // Generally local classes don't have it, and those from extensions and test suites do.
143  if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
144  $filePath = "$IP/$file";
145  } else {
146  $filePath = $file;
147  }
148 
149  if ( !file_exists( $filePath ) ) {
150  $actual[$class] = "[file '$filePath' does not exist]";
151  continue;
152  }
153 
154  Wikimedia\suppressWarnings();
155  $contents = file_get_contents( $filePath );
156  Wikimedia\restoreWarnings();
157 
158  if ( $contents === false ) {
159  $actual[$class] = "[couldn't read file '$filePath']";
160  continue;
161  }
162 
163  list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
164 
165  foreach ( $classesInFile as $className => $ignore ) {
166  // Skip if it's a PSR4 class
167  $parts = explode( '\\', $className );
168  for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
169  $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
170  if ( isset( $psr4Namespaces[$ns] ) ) {
171  $expectedPath = $psr4Namespaces[$ns] . '/'
172  . implode( '/', array_slice( $parts, $i ) )
173  . '.php';
174  if ( $filePath === $expectedPath ) {
175  continue 2;
176  }
177  }
178  }
179 
180  // Nope, add it.
181  $actual[$className] = $file;
182  }
183 
184  // Only accept aliases for classes in the same file, because for correct
185  // behavior, all aliases for a class must be set up when the class is loaded
186  // (see <https://bugs.php.net/bug.php?id=61422>).
187  foreach ( $aliasesInFile as $alias => $class ) {
188  if ( isset( $classesInFile[$class] ) ) {
189  $actual[$alias] = $file;
190  } else {
191  $actual[$alias] = "[original class not in $file]";
192  }
193  }
194  }
195 
196  return [
197  'expected' => $expected,
198  'actual' => $actual,
199  ];
200  }
201 
202  public function testAutoloadOrder() {
203  $path = realpath( __DIR__ . '/../../..' );
204  $oldAutoload = file_get_contents( $path . '/autoload.php' );
205  $generator = new AutoloadGenerator( $path, 'local' );
206  $generator->setPsr4Namespaces( AutoLoader::getAutoloadNamespaces() );
207  $generator->initMediaWikiDefault();
208  $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
209 
210  $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
211  ' output of generateLocalAutoload.php script.' );
212  }
213 }
AutoLoaderStructureTest\testPSR4Completeness
testPSR4Completeness( $prefix, $dir, $file)
providePSR4Completeness
Definition: AutoLoaderStructureTest.php:37
$wgAutoloadClasses
$wgAutoloadClasses['ReplaceTextHooks']
Definition: ReplaceText.php:61
captcha-old.count
count
Definition: captcha-old.py:249
AutoLoaderStructureTest\parseFile
static parseFile( $contents)
Definition: AutoLoaderStructureTest.php:74
AutoloadGenerator
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
Definition: AutoloadGenerator.php:16
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$matches
$matches
Definition: NoLocalSettings.php:24
MediaWikiTestCase
Definition: MediaWikiTestCase.php:16
$IP
$IP
Definition: update.php:3
AutoLoader\getAutoloadNamespaces
static getAutoloadNamespaces()
Get a mapping of namespace => file path The namespaces should follow the PSR-4 standard for autoloadi...
Definition: AutoLoader.php:130
AutoLoader\$psr4Namespaces
static string[] $psr4Namespaces
Definition: AutoLoader.php:37
$generator
$generator
Definition: generateLocalAutoload.php:13
$wgAutoloadLocalClasses
global $wgAutoloadLocalClasses
Definition: autoload.php:4
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
AutoLoaderStructureTest\testAutoLoadConfig
testAutoLoadConfig()
Assert that there were no classes loaded that are not registered with the AutoLoader.
Definition: AutoLoaderStructureTest.php:13
AutoLoaderStructureTest\providePSR4Completeness
providePSR4Completeness()
Definition: AutoLoaderStructureTest.php:22
AutoLoaderStructureTest\testAutoloadOrder
testAutoloadOrder()
Definition: AutoLoaderStructureTest.php:202
AutoLoaderStructureTest\checkAutoLoadConf
static checkAutoLoadConf()
Definition: AutoLoaderStructureTest.php:126
$path
$path
Definition: NoLocalSettings.php:25
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
AutoLoaderStructureTest\recurseFiles
recurseFiles( $dir)
Definition: AutoLoaderStructureTest.php:30
AutoLoaderStructureTest
@coversNothing
Definition: AutoLoaderStructureTest.php:6