MediaWiki  master
AutoLoaderStructureTest.php
Go to the documentation of this file.
1 <?php
2 
10  public function testAutoLoadConfig() {
11  $results = self::checkAutoLoadConf();
12 
13  $this->assertEquals(
14  $results['expected'],
15  $results['actual']
16  );
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 
27  private function recurseFiles( $dir ) {
28  return ( new File_Iterator_Facade() )->getFilesAsArray( $dir, [ '.php' ] );
29  }
30 
34  public function testPSR4Completeness( $prefix, $dir, $file ) {
36  $contents = file_get_contents( $file );
37  list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
38  $classes = array_keys( $classesInFile );
39  if ( $classes ) {
40  $this->assertCount(
41  1,
42  $classes,
43  "Only one class per file in PSR-4 autoloaded classes ($file)"
44  );
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  $dirNameLength = strlen( realpath( $dir ) ) + 1; // +1 for the trailing slash
50  $fileBaseName = substr( $file, $dirNameLength );
51  $abbrFileName = substr( $fileBaseName, 0, -4 );
52  $expectedClassName = $prefix . str_replace( '/', '\\', $abbrFileName );
53 
54  $this->assertSame(
55  $expectedClassName,
56  $classes[0],
57  "Class not autoloaded properly"
58  );
59 
60  } else {
61  // Dummy assertion so this test isn't marked in risky
62  // if the file has no classes nor aliases in it
63  $this->assertCount( 0, $classes );
64  }
65 
66  if ( $aliasesInFile ) {
67  $otherClasses = $wgAutoloadLocalClasses + $wgAutoloadClasses;
68  foreach ( $aliasesInFile as $alias => $class ) {
69  $this->assertArrayHasKey( $alias, $otherClasses,
70  'Alias must be in the classmap autoloader'
71  );
72  }
73  }
74  }
75 
76  private static function parseFile( $contents ) {
77  // We could use token_get_all() here, but this is faster
78  // Note: Keep in sync with ClassCollector
79  $matches = [];
80  preg_match_all( '/
81  ^ [\t ]* (?:
82  (?:final\s+)? (?:abstract\s+)? (?:class|interface|trait) \s+
83  (?P<class> \w+)
84  |
85  class_alias \s* \( \s*
86  ([\'"]) (?P<original> [^\'"]+) \g{-2} \s* , \s*
87  ([\'"]) (?P<alias> [^\'"]+ ) \g{-2} \s*
88  \) \s* ;
89  |
90  class_alias \s* \( \s*
91  (?P<originalStatic> [\w\\\\]+)::class \s* , \s*
92  ([\'"]) (?P<aliasString> [^\'"]+ ) \g{-2} \s*
93  \) \s* ;
94  )
95  /imx', $contents, $matches, PREG_SET_ORDER );
96 
97  $namespaceMatch = [];
98  preg_match( '/
99  ^ [\t ]*
100  namespace \s+
101  (\w+(\\\\\w+)*)
102  \s* ;
103  /imx', $contents, $namespaceMatch );
104  $fileNamespace = $namespaceMatch ? $namespaceMatch[1] . '\\' : '';
105 
106  $classesInFile = [];
107  $aliasesInFile = [];
108 
109  foreach ( $matches as $match ) {
110  if ( !empty( $match['class'] ) ) {
111  // 'class Foo {}'
112  $class = $fileNamespace . $match['class'];
113  $classesInFile[$class] = true;
114  } elseif ( !empty( $match['original'] ) ) {
115  // 'class_alias( "Foo", "Bar" );'
116  $aliasesInFile[$match['alias']] = $match['original'];
117  } else {
118  // 'class_alias( Foo::class, "Bar" );'
119  $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
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
130  $expected = $wgAutoloadLocalClasses + $wgAutoloadClasses;
131  $actual = [];
132 
133  $psr4Namespaces = [];
134  foreach ( AutoLoader::getAutoloadNamespaces() as $ns => $path ) {
135  $psr4Namespaces[rtrim( $ns, '\\' ) . '\\'] = rtrim( $path, '/' );
136  }
137 
138  foreach ( $expected as $class => $file ) {
139  // Only prefix $IP if it doesn't have it already.
140  // Generally local classes don't have it, and those from extensions and test suites do.
141  if ( substr( $file, 0, 1 ) != '/' && substr( $file, 1, 1 ) != ':' ) {
142  $filePath = "$IP/$file";
143  } else {
144  $filePath = $file;
145  }
146 
147  if ( !file_exists( $filePath ) ) {
148  $actual[$class] = "[file '$filePath' does not exist]";
149  continue;
150  }
151 
152  Wikimedia\suppressWarnings();
153  $contents = file_get_contents( $filePath );
154  Wikimedia\restoreWarnings();
155 
156  if ( $contents === false ) {
157  $actual[$class] = "[couldn't read file '$filePath']";
158  continue;
159  }
160 
161  list( $classesInFile, $aliasesInFile ) = self::parseFile( $contents );
162 
163  foreach ( $classesInFile as $className => $ignore ) {
164  // Skip if it's a PSR4 class
165  $parts = explode( '\\', $className );
166  for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
167  $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
168  if ( isset( $psr4Namespaces[$ns] ) ) {
169  $expectedPath = $psr4Namespaces[$ns] . '/'
170  . implode( '/', array_slice( $parts, $i ) )
171  . '.php';
172  if ( $filePath === $expectedPath ) {
173  continue 2;
174  }
175  }
176  }
177 
178  // Nope, add it.
179  $actual[$className] = $file;
180  }
181 
182  // Only accept aliases for classes in the same file, because for correct
183  // behavior, all aliases for a class must be set up when the class is loaded
184  // (see <https://bugs.php.net/bug.php?id=61422>).
185  foreach ( $aliasesInFile as $alias => $class ) {
186  if ( isset( $classesInFile[$class] ) ) {
187  $actual[$alias] = $file;
188  } else {
189  $actual[$alias] = "[original class not in $file]";
190  }
191  }
192  }
193 
194  return [
195  'expected' => $expected,
196  'actual' => $actual,
197  ];
198  }
199 
200  public function testAutoloadOrder() {
201  $path = __DIR__ . '/../../..';
202  $oldAutoload = file_get_contents( $path . '/autoload.php' );
203  $generator = new AutoloadGenerator( $path, 'local' );
204  $generator->setPsr4Namespaces( AutoLoader::getAutoloadNamespaces() );
205  $generator->initMediaWikiDefault();
206  $newAutoload = $generator->getAutoload( 'maintenance/generateLocalAutoload.php' );
207 
208  $this->assertEquals( $oldAutoload, $newAutoload, 'autoload.php does not match' .
209  ' output of generateLocalAutoload.php script.' );
210  }
211 }
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
$IP
Definition: WebStart.php:41
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
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
testAutoLoadConfig()
Assert that there were no classes loaded that are not registered with the AutoLoader.
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
global $wgAutoloadLocalClasses
Definition: autoload.php:4
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
$wgAutoloadClasses
Array mapping class names to filenames, for autoloading.
static getAutoloadNamespaces()
Get a mapping of namespace => file path The namespaces should follow the PSR-4 standard for autoloadi...
Definition: AutoLoader.php:130
static string [] $psr4Namespaces
Definition: AutoLoader.php:37
testPSR4Completeness( $prefix, $dir, $file)
providePSR4Completeness
$matches