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.
11 * $gen = new AutoloadGenerator( __DIR__ );
12 * $gen->readDir( __DIR__ . '/includes' );
13 * $gen->readFile( __DIR__ . '/foo.php' )
14 * $gen->generateAutoload();
16 class AutoloadGenerator
{
18 * @var string Root path of the project being scanned for classes
23 * @var ClassCollector Helper class extracts class names from php files
28 * @var array Map of file shortpath to list of FQCN detected within file
30 protected $classes = array();
33 * @var string The global variable to write output to
35 protected $variableName = 'wgAutoloadClasses';
38 * @var array Map of FQCN to relative path(from self::$basepath)
40 protected $overrides = array();
43 * @param string $basepath Root path of the project being scanned for classes
44 * @param array|string $flags
46 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
47 * of $wgAutoloadClasses
49 public function __construct( $basepath, $flags = array() ) {
50 if ( !is_array( $flags ) ) {
51 $flags = array( $flags );
53 $this->basepath
= self
::platformAgnosticRealpath( $basepath );
54 $this->collector
= new ClassCollector
;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName
= 'wgAutoloadLocalClasses';
61 * Wrapper for realpath() that returns the same results (using forward
62 * slashes) on both Windows and *nix.
64 * @param string $path Parameter to realpath()
67 protected static function platformAgnosticRealpath( $path ) {
68 return str_replace( '\\', '/', realpath( $path ) );
72 * Force a class to be autoloaded from a specific path, regardless of where
73 * or if it was detected.
75 * @param string $fqcn FQCN to force the location of
76 * @param string $inputPath Full path to the file containing the class
78 public function forceClassPath( $fqcn, $inputPath ) {
79 $path = self
::platformAgnosticRealpath( $inputPath );
81 throw new \
Exception( "Invalid path: $inputPath" );
83 $len = strlen( $this->basepath
);
84 if ( substr( $path, 0, $len ) !== $this->basepath
) {
85 throw new \
Exception( "Path is not within basepath: $inputPath" );
87 $shortpath = substr( $path, $len );
88 $this->overrides
[$fqcn] = $shortpath;
92 * @param string $inputPath Path to a php file to find classes within
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" );
100 $result = $this->collector
->getClasses(
101 file_get_contents( $inputPath )
104 $shortpath = substr( $inputPath, $len );
105 $this->classes
[$shortpath] = $result;
110 * @param string $dir Path to a directory to recursively search
111 * for php files with either .php or .inc extensions
113 public function readDir( $dir ) {
114 $it = new RecursiveDirectoryIterator(
115 self
::platformAgnosticRealpath( $dir ) );
116 $it = new RecursiveIteratorIterator( $it );
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 );
128 * Write out all known classes to autoload.php in
129 * the provided basedir
131 * @param string $commandName Value used in file comment to direct
132 * developers towards the appropriate way to update the autoload.
134 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
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(
145 var_export( $fqcn, true ),
151 foreach ( $this->overrides
as $fqcn => $path ) {
152 $content[$fqcn] = sprintf(
154 var_export( $fqcn, true ),
155 var_export( $path, true )
159 // sort for stable output
162 // extensions using this generator are appending to the existing
164 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
170 $output = implode( "\n\t", $content );
172 $this->basepath
. '/autoload.php',
175 // This file is generated by $commandName, do not adjust manually
177 global \${$this->variableName};
179 \${$this->variableName} {$op} array(
189 * Reads PHP code and returns the FQCN of every class defined within it.
191 class ClassCollector
{
194 * @var string Current namespace
196 protected $namespace = '';
199 * @var array List of FQCN detected in this pass
204 * @var array Token from token_get_all() that started an expect sequence
206 protected $startToken;
209 * @var array List of tokens that are members of the current expect sequence
214 * @var string $code PHP code (including <?php) to detect class names from
215 * @return array List of FQCN detected within the tokens
217 public function getClasses( $code ) {
218 $this->namespace = '';
219 $this->classes
= array();
220 $this->startToken
= null;
221 $this->tokens
= array();
223 foreach ( token_get_all( $code ) as $token ) {
224 if ( $this->startToken
=== null ) {
225 $this->tryBeginExpect( $token );
227 $this->tryEndExpect( $token );
231 return $this->classes
;
235 * Determine if $token begins the next expect sequence.
237 * @param array $token
239 protected function tryBeginExpect( $token ) {
240 if ( is_string( $token ) ) {
243 switch ( $token[0] ) {
247 $this->startToken
= $token;
252 * Accepts the next token in an expect sequence
256 protected function tryEndExpect( $token ) {
257 switch ( $this->startToken
[0] ) {
259 if ( $token === ';' ||
$token === '{' ) {
260 $this->namespace = $this->implodeTokens() . '\\';
262 $this->tokens
[] = $token;
268 $this->tokens
[] = $token;
269 if ( is_array( $token ) && $token[0] === T_STRING
) {
270 $this->classes
[] = $this->namespace . $this->implodeTokens();
276 * Returns the string representation of the tokens within the
277 * current expect sequence and resets the sequence.
281 protected function implodeTokens() {
283 foreach ( $this->tokens
as $token ) {
284 $content[] = is_string( $token ) ?
$token : $token[1];
287 $this->tokens
= array();
288 $this->startToken
= null;
290 return trim( implode( '', $content ), " \n\t" );