Merge "Tidy up tidy usage"
[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 = array();
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 = array();
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 = array() ) {
50 if ( !is_array( $flags ) ) {
51 $flags = array( $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 * Write out all known classes to autoload.php in
123 * the provided basedir
124 *
125 * @param string $commandName Value used in file comment to direct
126 * developers towards the appropriate way to update the autoload.
127 */
128 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
129 $content = array();
130
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
141 );
142 }
143 }
144
145 foreach ( $this->overrides as $fqcn => $path ) {
146 $content[$fqcn] = sprintf(
147 $format,
148 var_export( $fqcn, true ),
149 var_export( $path, true )
150 );
151 }
152
153 // sort for stable output
154 ksort( $content );
155
156 // extensions using this generator are appending to the existing
157 // autoload.
158 if ( $this->variableName === 'wgAutoloadClasses' ) {
159 $op = '+=';
160 } else {
161 $op = '=';
162 }
163
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
170 // @codingStandardsIgnoreFile
171 global \${$this->variableName};
172
173 \${$this->variableName} {$op} array(
174 {$output}
175 );
176
177 EOD
178 );
179 }
180
181 /**
182 * Ensure that Unix-style path separators ("/") are used in the path.
183 *
184 * @param string $path
185 * @return string
186 */
187 protected static function normalizePathSeparator( $path ) {
188 return str_replace( '\\', '/', $path );
189 }
190 }
191
192 /**
193 * Reads PHP code and returns the FQCN of every class defined within it.
194 */
195 class ClassCollector {
196
197 /**
198 * @var string Current namespace
199 */
200 protected $namespace = '';
201
202 /**
203 * @var array List of FQCN detected in this pass
204 */
205 protected $classes;
206
207 /**
208 * @var array Token from token_get_all() that started an expect sequence
209 */
210 protected $startToken;
211
212 /**
213 * @var array List of tokens that are members of the current expect sequence
214 */
215 protected $tokens;
216
217 /**
218 * @var string $code PHP code (including <?php) to detect class names from
219 * @return array List of FQCN detected within the tokens
220 */
221 public function getClasses( $code ) {
222 $this->namespace = '';
223 $this->classes = array();
224 $this->startToken = null;
225 $this->tokens = array();
226
227 foreach ( token_get_all( $code ) as $token ) {
228 if ( $this->startToken === null ) {
229 $this->tryBeginExpect( $token );
230 } else {
231 $this->tryEndExpect( $token );
232 }
233 }
234
235 return $this->classes;
236 }
237
238 /**
239 * Determine if $token begins the next expect sequence.
240 *
241 * @param array $token
242 */
243 protected function tryBeginExpect( $token ) {
244 if ( is_string( $token ) ) {
245 return;
246 }
247 switch ( $token[0] ) {
248 case T_NAMESPACE:
249 case T_CLASS:
250 case T_INTERFACE:
251 $this->startToken = $token;
252 }
253 }
254
255 /**
256 * Accepts the next token in an expect sequence
257 *
258 * @param array
259 */
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;
267 }
268 break;
269
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();
275 }
276 }
277 }
278
279 /**
280 * Returns the string representation of the tokens within the
281 * current expect sequence and resets the sequence.
282 *
283 * @return string
284 */
285 protected function implodeTokens() {
286 $content = array();
287 foreach ( $this->tokens as $token ) {
288 $content[] = is_string( $token ) ? $token : $token[1];
289 }
290
291 $this->tokens = array();
292 $this->startToken = null;
293
294 return trim( implode( '', $content ), " \n\t" );
295 }
296 }