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