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