6149a23f331c5bdc3bab5d61583fb7584998345f
[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::platformAgnosticRealpath( $basepath );
54 $this->collector = new ClassCollector;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName = 'wgAutoloadLocalClasses';
57 }
58 }
59
60 /**
61 * Wrapper for realpath() that returns the same results (using forward
62 * slashes) on both Windows and *nix.
63 *
64 * @param string $path Parameter to realpath()
65 * @return string
66 */
67 protected static function platformAgnosticRealpath( $path ) {
68 return str_replace( '\\', '/', realpath( $path ) );
69 }
70
71 /**
72 * Force a class to be autoloaded from a specific path, regardless of where
73 * or if it was detected.
74 *
75 * @param string $fqcn FQCN to force the location of
76 * @param string $inputPath Full path to the file containing the class
77 */
78 public function forceClassPath( $fqcn, $inputPath ) {
79 $path = self::platformAgnosticRealpath( $inputPath );
80 if ( !$path ) {
81 throw new \Exception( "Invalid path: $inputPath" );
82 }
83 $len = strlen( $this->basepath );
84 if ( substr( $path, 0, $len ) !== $this->basepath ) {
85 throw new \Exception( "Path is not within basepath: $inputPath" );
86 }
87 $shortpath = substr( $path, $len );
88 $this->overrides[$fqcn] = $shortpath;
89 }
90
91 /**
92 * @param string $inputPath Path to a php file to find classes within
93 */
94 public function readFile( $inputPath ) {
95 $inputPath = self::platformAgnosticRealpath( $inputPath );
96 $len = strlen( $this->basepath );
97 if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
98 throw new \Exception( "Path is not within basepath: $inputPath" );
99 }
100 $result = $this->collector->getClasses(
101 file_get_contents( $inputPath )
102 );
103 if ( $result ) {
104 $shortpath = substr( $inputPath, $len );
105 $this->classes[$shortpath] = $result;
106 }
107 }
108
109 /**
110 * @param string $dir Path to a directory to recursively search
111 * for php files with either .php or .inc extensions
112 */
113 public function readDir( $dir ) {
114 $it = new RecursiveDirectoryIterator(
115 self::platformAgnosticRealpath( $dir ) );
116 $it = new RecursiveIteratorIterator( $it );
117
118 foreach ( $it as $path => $file ) {
119 $ext = pathinfo( $path, PATHINFO_EXTENSION );
120 // some older files in mw use .inc
121 if ( $ext === 'php' || $ext === 'inc' ) {
122 $this->readFile( $path );
123 }
124 }
125 }
126
127 /**
128 * Write out all known classes to autoload.php in
129 * the provided basedir
130 *
131 * @param string $commandName Value used in file comment to direct
132 * developers towards the appropriate way to update the autoload.
133 */
134 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
135 $content = array();
136
137 // We need to generate a line each rather than exporting the
138 // full array so __DIR__ can be prepended to all the paths
139 $format = "%s => __DIR__ . %s,";
140 foreach ( $this->classes as $path => $contained ) {
141 $exportedPath = var_export( $path, true );
142 foreach ( $contained as $fqcn ) {
143 $content[$fqcn] = sprintf(
144 $format,
145 var_export( $fqcn, true ),
146 $exportedPath
147 );
148 }
149 }
150
151 foreach ( $this->overrides as $fqcn => $path ) {
152 $content[$fqcn] = sprintf(
153 $format,
154 var_export( $fqcn, true ),
155 var_export( $path, true )
156 );
157 }
158
159 // sort for stable output
160 ksort( $content );
161
162 // extensions using this generator are appending to the existing
163 // autoload.
164 if ( $this->variableName === 'wgAutoloadClasses' ) {
165 $op = '+=';
166 } else {
167 $op = '=';
168 }
169
170 $output = implode( "\n\t", $content );
171 file_put_contents(
172 $this->basepath . '/autoload.php',
173 <<<EOD
174 <?php
175 // This file is generated by $commandName, do not adjust manually
176
177 global \${$this->variableName};
178
179 \${$this->variableName} {$op} array(
180 {$output}
181 );
182
183 EOD
184 );
185 }
186 }
187
188 /**
189 * Reads PHP code and returns the FQCN of every class defined within it.
190 */
191 class ClassCollector {
192
193 /**
194 * @var string Current namespace
195 */
196 protected $namespace = '';
197
198 /**
199 * @var array List of FQCN detected in this pass
200 */
201 protected $classes;
202
203 /**
204 * @var array Token from token_get_all() that started an expect sequence
205 */
206 protected $startToken;
207
208 /**
209 * @var array List of tokens that are members of the current expect sequence
210 */
211 protected $tokens;
212
213 /**
214 * @var string $code PHP code (including <?php) to detect class names from
215 * @return array List of FQCN detected within the tokens
216 */
217 public function getClasses( $code ) {
218 $this->namespace = '';
219 $this->classes = array();
220 $this->startToken = null;
221 $this->tokens = array();
222
223 foreach ( token_get_all( $code ) as $token ) {
224 if ( $this->startToken === null ) {
225 $this->tryBeginExpect( $token );
226 } else {
227 $this->tryEndExpect( $token );
228 }
229 }
230
231 return $this->classes;
232 }
233
234 /**
235 * Determine if $token begins the next expect sequence.
236 *
237 * @param array $token
238 */
239 protected function tryBeginExpect( $token ) {
240 if ( is_string( $token ) ) {
241 return;
242 }
243 switch ( $token[0] ) {
244 case T_NAMESPACE:
245 case T_CLASS:
246 case T_INTERFACE:
247 $this->startToken = $token;
248 }
249 }
250
251 /**
252 * Accepts the next token in an expect sequence
253 *
254 * @param array
255 */
256 protected function tryEndExpect( $token ) {
257 switch ( $this->startToken[0] ) {
258 case T_NAMESPACE:
259 if ( $token === ';' || $token === '{' ) {
260 $this->namespace = $this->implodeTokens() . '\\';
261 } else {
262 $this->tokens[] = $token;
263 }
264 break;
265
266 case T_CLASS:
267 case T_INTERFACE:
268 $this->tokens[] = $token;
269 if ( is_array( $token ) && $token[0] === T_STRING ) {
270 $this->classes[] = $this->namespace . $this->implodeTokens();
271 }
272 }
273 }
274
275 /**
276 * Returns the string representation of the tokens within the
277 * current expect sequence and resets the sequence.
278 *
279 * @return string
280 */
281 protected function implodeTokens() {
282 $content = array();
283 foreach ( $this->tokens as $token ) {
284 $content[] = is_string( $token ) ? $token : $token[1];
285 }
286
287 $this->tokens = array();
288 $this->startToken = null;
289
290 return trim( implode( '', $content ), " \n\t" );
291 }
292 }