Merge "FormatMetadata::fetchExtendedMetadata: Ignore multiple EXIF/XMP values"
[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 $path = realpath( $inputPath );
85 if ( !$path ) {
86 throw new \Exception( "Invalid path: $inputPath" );
87 }
88 $len = strlen( $this->basepath );
89 if ( substr( $path, 0, $len ) !== $this->basepath ) {
90 throw new \Exception( "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 * @param string $commandName Value used in file comment to direct
123 * developers towards the appropriate way to update the autoload.
124 */
125 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
126 $content = array();
127
128 // We need to generate a line each rather than exporting the
129 // full array so __DIR__ can be prepended to all the paths
130 $format = "%s => __DIR__ . %s,";
131 foreach ( $this->classes as $path => $contained ) {
132 $exportedPath = var_export( $path, true );
133 foreach ( $contained as $fqcn ) {
134 $content[$fqcn] = sprintf(
135 $format,
136 var_export( $fqcn, true ),
137 $exportedPath
138 );
139 }
140 }
141
142 foreach ( $this->overrides as $fqcn => $path ) {
143 $content[$fqcn] = sprintf(
144 $format,
145 var_export( $fqcn, true ),
146 var_export( $path, true )
147 );
148 }
149
150 // sort for stable output
151 ksort( $content );
152
153 // extensions using this generator are appending to the existing
154 // autoload.
155 if ( $this->variableName === 'wgAutoloadClasses' ) {
156 $op = '+=';
157 } else {
158 $op = '=';
159 }
160
161 $output = implode( "\n\t", $content );
162 file_put_contents(
163 $this->basepath . '/autoload.php',
164 <<<EOD
165 <?php
166 // This file is generated by $commandName, do not adjust manually
167
168 global \${$this->variableName};
169
170 \${$this->variableName} {$op} array(
171 {$output}
172 );
173
174 EOD
175 );
176 }
177 }
178
179 /**
180 * Reads PHP code and returns the FQCN of every class defined within it.
181 */
182 class ClassCollector {
183
184 /**
185 * @var string Current namespace
186 */
187 protected $namespace = '';
188
189 /**
190 * @var array List of FQCN detected in this pass
191 */
192 protected $classes;
193
194 /**
195 * @var array Token from token_get_all() that started an expect sequence
196 */
197 protected $startToken;
198
199 /**
200 * @var array List of tokens that are members of the current expect sequence
201 */
202 protected $tokens;
203
204 /**
205 * @var string $code PHP code (including <?php) to detect class names from
206 * @return array List of FQCN detected within the tokens
207 */
208 public function getClasses( $code ) {
209 $this->namespace = '';
210 $this->classes = array();
211 $this->startToken = null;
212 $this->tokens = array();
213
214 foreach ( token_get_all( $code ) as $token ) {
215 if ( $this->startToken === null ) {
216 $this->tryBeginExpect( $token );
217 } else {
218 $this->tryEndExpect( $token );
219 }
220 }
221
222 return $this->classes;
223 }
224
225 /**
226 * Determine if $token begins the next expect sequence.
227 *
228 * @param array $token
229 */
230 protected function tryBeginExpect( $token ) {
231 if ( is_string( $token ) ) {
232 return;
233 }
234 switch( $token[0] ) {
235 case T_NAMESPACE:
236 case T_CLASS:
237 case T_INTERFACE:
238 $this->startToken = $token;
239 }
240 }
241
242 /**
243 * Accepts the next token in an expect sequence
244 *
245 * @param array
246 */
247 protected function tryEndExpect( $token ) {
248 switch( $this->startToken[0] ) {
249 case T_NAMESPACE:
250 if ( $token === ';' || $token === '{' ) {
251 $this->namespace = $this->implodeTokens() . '\\';
252 } else {
253 $this->tokens[] = $token;
254 }
255 break;
256
257 case T_CLASS:
258 case T_INTERFACE:
259 $this->tokens[] = $token;
260 if ( is_array( $token ) && $token[0] === T_STRING ) {
261 $this->classes[] = $this->namespace . $this->implodeTokens();
262 }
263 }
264 }
265
266 /**
267 * Returns the string representation of the tokens within the
268 * current expect sequence and resets the sequence.
269 *
270 * @return string
271 */
272 protected function implodeTokens() {
273 $content = array();
274 foreach ( $this->tokens as $token ) {
275 $content[] = is_string( $token ) ? $token : $token[1];
276 }
277
278 $this->tokens = array();
279 $this->startToken = null;
280
281 return trim( implode( '', $content ), " \n\t" );
282 }
283 }