Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / utils / AutoloadGenerator.php
blob1f639fc4ff5f8c4ebe0e368f8c9aafe633e755a1
1 <?php
3 /**
4 * Accepts a list of files and directories to search for
5 * php files and generates $wgAutoloadLocalClasses or $wgAutoloadClasses
6 * lines for all detected classes. These lines are written out
7 * to an autoload.php file in the projects provided basedir.
9 * Usage:
11 * $gen = new AutoloadGenerator( __DIR__ );
12 * $gen->readDir( __DIR__ . '/includes' );
13 * $gen->readFile( __DIR__ . '/foo.php' )
14 * $gen->generateAutoload();
16 class AutoloadGenerator {
17 /**
18 * @var string Root path of the project being scanned for classes
20 protected $basepath;
22 /**
23 * @var ClassCollector Helper class extracts class names from php files
25 protected $collector;
27 /**
28 * @var array Map of file shortpath to list of FQCN detected within file
30 protected $classes = array();
32 /**
33 * @var string The global variable to write output to
35 protected $variableName = 'wgAutoloadClasses';
37 /**
38 * @var array Map of FQCN to relative path(from self::$basepath)
40 protected $overrides = array();
42 /**
43 * @param string $basepath Root path of the project being scanned for classes
44 * @param array|string $flags
46 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
47 * of $wgAutoloadClasses
49 public function __construct( $basepath, $flags = array() ) {
50 if ( !is_array( $flags ) ) {
51 $flags = array( $flags );
53 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
54 $this->collector = new ClassCollector;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName = 'wgAutoloadLocalClasses';
60 /**
61 * Force a class to be autoloaded from a specific path, regardless of where
62 * or if it was detected.
64 * @param string $fqcn FQCN to force the location of
65 * @param string $inputPath Full path to the file containing the class
66 * @throws Exception
68 public function forceClassPath( $fqcn, $inputPath ) {
69 $path = self::normalizePathSeparator( realpath( $inputPath ) );
70 if ( !$path ) {
71 throw new \Exception( "Invalid path: $inputPath" );
73 $len = strlen( $this->basepath );
74 if ( substr( $path, 0, $len ) !== $this->basepath ) {
75 throw new \Exception( "Path is not within basepath: $inputPath" );
77 $shortpath = substr( $path, $len );
78 $this->overrides[$fqcn] = $shortpath;
81 /**
82 * @param string $inputPath Path to a php file to find classes within
83 * @throws Exception
85 public function readFile( $inputPath ) {
86 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
87 // reasonable for LocalSettings.php and similiar files to be symlinks
88 // to files that are outside of $this->basepath.
89 $inputPath = self::normalizePathSeparator( $inputPath );
90 $len = strlen( $this->basepath );
91 if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
92 throw new \Exception( "Path is not within basepath: $inputPath" );
94 $result = $this->collector->getClasses(
95 file_get_contents( $inputPath )
97 if ( $result ) {
98 $shortpath = substr( $inputPath, $len );
99 $this->classes[$shortpath] = $result;
104 * @param string $dir Path to a directory to recursively search
105 * for php files with either .php or .inc extensions
107 public function readDir( $dir ) {
108 $it = new RecursiveDirectoryIterator(
109 self::normalizePathSeparator( realpath( $dir ) ) );
110 $it = new RecursiveIteratorIterator( $it );
112 foreach ( $it as $path => $file ) {
113 $ext = pathinfo( $path, PATHINFO_EXTENSION );
114 // some older files in mw use .inc
115 if ( $ext === 'php' || $ext === 'inc' ) {
116 $this->readFile( $path );
122 * Write out all known classes to autoload.php in
123 * the provided basedir
125 * @param string $commandName Value used in file comment to direct
126 * developers towards the appropriate way to update the autoload.
128 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
129 $content = array();
131 // We need to generate a line each rather than exporting the
132 // full array so __DIR__ can be prepended to all the paths
133 $format = "%s => __DIR__ . %s,";
134 foreach ( $this->classes as $path => $contained ) {
135 $exportedPath = var_export( $path, true );
136 foreach ( $contained as $fqcn ) {
137 $content[$fqcn] = sprintf(
138 $format,
139 var_export( $fqcn, true ),
140 $exportedPath
145 foreach ( $this->overrides as $fqcn => $path ) {
146 $content[$fqcn] = sprintf(
147 $format,
148 var_export( $fqcn, true ),
149 var_export( $path, true )
153 // sort for stable output
154 ksort( $content );
156 // extensions using this generator are appending to the existing
157 // autoload.
158 if ( $this->variableName === 'wgAutoloadClasses' ) {
159 $op = '+=';
160 } else {
161 $op = '=';
164 $output = implode( "\n\t", $content );
165 file_put_contents(
166 $this->basepath . '/autoload.php',
167 <<<EOD
168 <?php
169 // This file is generated by $commandName, do not adjust manually
171 global \${$this->variableName};
173 \${$this->variableName} {$op} array(
174 {$output}
182 * Ensure that Unix-style path separators ("/") are used in the path.
184 * @param string $path
185 * @return string
187 protected static function normalizePathSeparator( $path ) {
188 return str_replace( '\\', '/', $path );
193 * Reads PHP code and returns the FQCN of every class defined within it.
195 class ClassCollector {
198 * @var string Current namespace
200 protected $namespace = '';
203 * @var array List of FQCN detected in this pass
205 protected $classes;
208 * @var array Token from token_get_all() that started an expect sequence
210 protected $startToken;
213 * @var array List of tokens that are members of the current expect sequence
215 protected $tokens;
218 * @var string $code PHP code (including <?php) to detect class names from
219 * @return array List of FQCN detected within the tokens
221 public function getClasses( $code ) {
222 $this->namespace = '';
223 $this->classes = array();
224 $this->startToken = null;
225 $this->tokens = array();
227 foreach ( token_get_all( $code ) as $token ) {
228 if ( $this->startToken === null ) {
229 $this->tryBeginExpect( $token );
230 } else {
231 $this->tryEndExpect( $token );
235 return $this->classes;
239 * Determine if $token begins the next expect sequence.
241 * @param array $token
243 protected function tryBeginExpect( $token ) {
244 if ( is_string( $token ) ) {
245 return;
247 switch ( $token[0] ) {
248 case T_NAMESPACE:
249 case T_CLASS:
250 case T_INTERFACE:
251 $this->startToken = $token;
256 * Accepts the next token in an expect sequence
258 * @param array
260 protected function tryEndExpect( $token ) {
261 switch ( $this->startToken[0] ) {
262 case T_NAMESPACE:
263 if ( $token === ';' || $token === '{' ) {
264 $this->namespace = $this->implodeTokens() . '\\';
265 } else {
266 $this->tokens[] = $token;
268 break;
270 case T_CLASS:
271 case T_INTERFACE:
272 $this->tokens[] = $token;
273 if ( is_array( $token ) && $token[0] === T_STRING ) {
274 $this->classes[] = $this->namespace . $this->implodeTokens();
280 * Returns the string representation of the tokens within the
281 * current expect sequence and resets the sequence.
283 * @return string
285 protected function implodeTokens() {
286 $content = array();
287 foreach ( $this->tokens as $token ) {
288 $content[] = is_string( $token ) ? $token : $token[1];
291 $this->tokens = array();
292 $this->startToken = null;
294 return trim( implode( '', $content ), " \n\t" );