Merge "Http::getProxy() method to get proxy configuration"
[lhc/web/wiklou.git] / includes / utils / AutoloadGenerator.php
1 <?php
2
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.
8 *
9 * Usage:
10 *
11 * $gen = new AutoloadGenerator( __DIR__ );
12 * $gen->readDir( __DIR__ . '/includes' );
13 * $gen->readFile( __DIR__ . '/foo.php' )
14 * $gen->generateAutoload();
15 */
16 class AutoloadGenerator {
17 /**
18 * @var string Root path of the project being scanned for classes
19 */
20 protected $basepath;
21
22 /**
23 * @var ClassCollector Helper class extracts class names from php files
24 */
25 protected $collector;
26
27 /**
28 * @var array Map of file shortpath to list of FQCN detected within file
29 */
30 protected $classes = [];
31
32 /**
33 * @var string The global variable to write output to
34 */
35 protected $variableName = 'wgAutoloadClasses';
36
37 /**
38 * @var array Map of FQCN to relative path(from self::$basepath)
39 */
40 protected $overrides = [];
41
42 /**
43 * @param string $basepath Root path of the project being scanned for classes
44 * @param array|string $flags
45 *
46 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
47 * of $wgAutoloadClasses
48 */
49 public function __construct( $basepath, $flags = [] ) {
50 if ( !is_array( $flags ) ) {
51 $flags = [ $flags ];
52 }
53 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
54 $this->collector = new ClassCollector;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName = 'wgAutoloadLocalClasses';
57 }
58 }
59
60 /**
61 * Force a class to be autoloaded from a specific path, regardless of where
62 * or if it was detected.
63 *
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
67 */
68 public function forceClassPath( $fqcn, $inputPath ) {
69 $path = self::normalizePathSeparator( realpath( $inputPath ) );
70 if ( !$path ) {
71 throw new \Exception( "Invalid path: $inputPath" );
72 }
73 $len = strlen( $this->basepath );
74 if ( substr( $path, 0, $len ) !== $this->basepath ) {
75 throw new \Exception( "Path is not within basepath: $inputPath" );
76 }
77 $shortpath = substr( $path, $len );
78 $this->overrides[$fqcn] = $shortpath;
79 }
80
81 /**
82 * @param string $inputPath Path to a php file to find classes within
83 * @throws Exception
84 */
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" );
93 }
94 $result = $this->collector->getClasses(
95 file_get_contents( $inputPath )
96 );
97 if ( $result ) {
98 $shortpath = substr( $inputPath, $len );
99 $this->classes[$shortpath] = $result;
100 }
101 }
102
103 /**
104 * @param string $dir Path to a directory to recursively search
105 * for php files with either .php or .inc extensions
106 */
107 public function readDir( $dir ) {
108 $it = new RecursiveDirectoryIterator(
109 self::normalizePathSeparator( realpath( $dir ) ) );
110 $it = new RecursiveIteratorIterator( $it );
111
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 );
117 }
118 }
119 }
120
121 /**
122 * Updates the AutoloadClasses field at the given
123 * filename.
124 *
125 * @param {string} $filename Filename of JSON
126 * extension/skin registration file
127 */
128 protected function generateJsonAutoload( $filename ) {
129 require_once __DIR__ . '/../../includes/json/FormatJson.php';
130 $key = 'AutoloadClasses';
131 $json = FormatJson::decode( file_get_contents( $filename ), true );
132 unset( $json[$key] );
133 // Inverting the key-value pairs so that they become of the
134 // format class-name : path when they get converted into json.
135 foreach ( $this->classes as $path => $contained ) {
136 foreach ( $contained as $fqcn ) {
137
138 // Using substr to remove the leading '/'
139 $json[$key][$fqcn] = substr( $path, 1 );
140 }
141 }
142 foreach ( $this->overrides as $path => $fqcn ) {
143
144 // Using substr to remove the leading '/'
145 $json[$key][$fqcn] = substr( $path, 1 );
146 }
147
148 // Sorting the list of autoload classes.
149 ksort( $json[$key] );
150
151 // Update file, using constants for the required
152 // formatting.
153 file_put_contents( $filename,
154 FormatJson::encode( $json, true ) . "\n" );
155 }
156
157 /**
158 * Generates a PHP file setting up autoload information.
159 *
160 * @param {string} $commandName Command name to include in comment
161 * @param {string} $filename of PHP file to put autoload information in.
162 */
163 protected function generatePHPAutoload( $commandName, $filename ) {
164 // No existing JSON file found; update/generate PHP file
165 $content = [];
166
167 // We need to generate a line each rather than exporting the
168 // full array so __DIR__ can be prepended to all the paths
169 $format = "%s => __DIR__ . %s,";
170 foreach ( $this->classes as $path => $contained ) {
171 $exportedPath = var_export( $path, true );
172 foreach ( $contained as $fqcn ) {
173 $content[$fqcn] = sprintf(
174 $format,
175 var_export( $fqcn, true ),
176 $exportedPath
177 );
178 }
179 }
180
181 foreach ( $this->overrides as $fqcn => $path ) {
182 $content[$fqcn] = sprintf(
183 $format,
184 var_export( $fqcn, true ),
185 var_export( $path, true )
186 );
187 }
188
189 // sort for stable output
190 ksort( $content );
191
192 // extensions using this generator are appending to the existing
193 // autoload.
194 if ( $this->variableName === 'wgAutoloadClasses' ) {
195 $op = '+=';
196 } else {
197 $op = '=';
198 }
199
200 $output = implode( "\n\t", $content );
201 file_put_contents(
202 $filename,
203 <<<EOD
204 <?php
205 // This file is generated by $commandName, do not adjust manually
206 // @codingStandardsIgnoreFile
207 global \${$this->variableName};
208
209 \${$this->variableName} {$op} [
210 {$output}
211 ];
212
213 EOD
214 );
215
216 }
217
218 /**
219 * Write out all known classes to autoload.php, extension.json, or skin.json in
220 * the provided basedir
221 *
222 * @param string $commandName Value used in file comment to direct
223 * developers towards the appropriate way to update the autoload.
224 */
225 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
226
227 // We need to check whether an extenson.json or skin.json exists or not, and
228 // incase it doesn't, update the autoload.php file.
229
230 $jsonFilename = null;
231 if ( file_exists( $this->basepath . "/extension.json" ) ) {
232 $jsonFilename = $this->basepath . "/extension.json";
233 } elseif ( file_exists( $this->basepath . "/skin.json" ) ) {
234 $jsonFilename = $this->basepath . "/skin.json";
235 }
236
237 if ( $jsonFilename !== null ) {
238 $this->generateJsonAutoload( $jsonFilename );
239 } else {
240 $this->generatePHPAutoload( $commandName, $this->basepath . '/autoload.php' );
241 }
242 }
243 /**
244 * Ensure that Unix-style path separators ("/") are used in the path.
245 *
246 * @param string $path
247 * @return string
248 */
249 protected static function normalizePathSeparator( $path ) {
250 return str_replace( '\\', '/', $path );
251 }
252 }
253
254 /**
255 * Reads PHP code and returns the FQCN of every class defined within it.
256 */
257 class ClassCollector {
258
259 /**
260 * @var string Current namespace
261 */
262 protected $namespace = '';
263
264 /**
265 * @var array List of FQCN detected in this pass
266 */
267 protected $classes;
268
269 /**
270 * @var array Token from token_get_all() that started an expect sequence
271 */
272 protected $startToken;
273
274 /**
275 * @var array List of tokens that are members of the current expect sequence
276 */
277 protected $tokens;
278
279 /**
280 * @var string $code PHP code (including <?php) to detect class names from
281 * @return array List of FQCN detected within the tokens
282 */
283 public function getClasses( $code ) {
284 $this->namespace = '';
285 $this->classes = [];
286 $this->startToken = null;
287 $this->tokens = [];
288
289 foreach ( token_get_all( $code ) as $token ) {
290 if ( $this->startToken === null ) {
291 $this->tryBeginExpect( $token );
292 } else {
293 $this->tryEndExpect( $token );
294 }
295 }
296
297 return $this->classes;
298 }
299
300 /**
301 * Determine if $token begins the next expect sequence.
302 *
303 * @param array $token
304 */
305 protected function tryBeginExpect( $token ) {
306 if ( is_string( $token ) ) {
307 return;
308 }
309 switch ( $token[0] ) {
310 case T_NAMESPACE:
311 case T_CLASS:
312 case T_INTERFACE:
313 case T_TRAIT:
314 case T_DOUBLE_COLON:
315 $this->startToken = $token;
316 }
317 }
318
319 /**
320 * Accepts the next token in an expect sequence
321 *
322 * @param array
323 */
324 protected function tryEndExpect( $token ) {
325 switch ( $this->startToken[0] ) {
326 case T_DOUBLE_COLON:
327 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
328 // "self::static" which accesses the class name. It doens't define a new class.
329 $this->startToken = null;
330 break;
331 case T_NAMESPACE:
332 if ( $token === ';' || $token === '{' ) {
333 $this->namespace = $this->implodeTokens() . '\\';
334 } else {
335 $this->tokens[] = $token;
336 }
337 break;
338
339 case T_CLASS:
340 case T_INTERFACE:
341 case T_TRAIT:
342 $this->tokens[] = $token;
343 if ( is_array( $token ) && $token[0] === T_STRING ) {
344 $this->classes[] = $this->namespace . $this->implodeTokens();
345 }
346 }
347 }
348
349 /**
350 * Returns the string representation of the tokens within the
351 * current expect sequence and resets the sequence.
352 *
353 * @return string
354 */
355 protected function implodeTokens() {
356 $content = [];
357 foreach ( $this->tokens as $token ) {
358 $content[] = is_string( $token ) ? $token : $token[1];
359 }
360
361 $this->tokens = [];
362 $this->startToken = null;
363
364 return trim( implode( '', $content ), " \n\t" );
365 }
366 }