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
::normalizePathSeparator( realpath( $basepath ) );
54 $this->collector
= new ClassCollector
;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName
= 'wgAutoloadLocalClasses';
61 * Force a class to be autoloaded from a specific path, regardless of where
62 * or if it was detected.
64 * @param string $fqcn FQCN to force the location of
65 * @param string $inputPath Full path to the file containing the class
67 public function forceClassPath( $fqcn, $inputPath ) {
68 $path = self
::normalizePathSeparator( realpath( $inputPath ) );
70 throw new \
Exception( "Invalid path: $inputPath" );
72 $len = strlen( $this->basepath
);
73 if ( substr( $path, 0, $len ) !== $this->basepath
) {
74 throw new \
Exception( "Path is not within basepath: $inputPath" );
76 $shortpath = substr( $path, $len );
77 $this->overrides
[$fqcn] = $shortpath;
81 * @param string $inputPath Path to a php file to find classes within
83 public function readFile( $inputPath ) {
84 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
85 // reasonable for LocalSettings.php and similiar files to be symlinks
86 // to files that are outside of $this->basepath.
87 $inputPath = self
::normalizePathSeparator( $inputPath );
88 $len = strlen( $this->basepath
);
89 if ( substr( $inputPath, 0, $len ) !== $this->basepath
) {
90 throw new \
Exception( "Path is not within basepath: $inputPath" );
92 $result = $this->collector
->getClasses(
93 file_get_contents( $inputPath )
96 $shortpath = substr( $inputPath, $len );
97 $this->classes
[$shortpath] = $result;
102 * @param string $dir Path to a directory to recursively search
103 * for php files with either .php or .inc extensions
105 public function readDir( $dir ) {
106 $it = new RecursiveDirectoryIterator(
107 self
::normalizePathSeparator( realpath( $dir ) ) );
108 $it = new RecursiveIteratorIterator( $it );
110 foreach ( $it as $path => $file ) {
111 $ext = pathinfo( $path, PATHINFO_EXTENSION
);
112 // some older files in mw use .inc
113 if ( $ext === 'php' ||
$ext === 'inc' ) {
114 $this->readFile( $path );
120 * Write out all known classes to autoload.php in
121 * the provided basedir
123 * @param string $commandName Value used in file comment to direct
124 * developers towards the appropriate way to update the autoload.
126 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
129 // We need to generate a line each rather than exporting the
130 // full array so __DIR__ can be prepended to all the paths
131 $format = "%s => __DIR__ . %s,";
132 foreach ( $this->classes
as $path => $contained ) {
133 $exportedPath = var_export( $path, true );
134 foreach ( $contained as $fqcn ) {
135 $content[$fqcn] = sprintf(
137 var_export( $fqcn, true ),
143 foreach ( $this->overrides
as $fqcn => $path ) {
144 $content[$fqcn] = sprintf(
146 var_export( $fqcn, true ),
147 var_export( $path, true )
151 // sort for stable output
154 // extensions using this generator are appending to the existing
156 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
162 $output = implode( "\n\t", $content );
164 $this->basepath
. '/autoload.php',
167 // This file is generated by $commandName, do not adjust manually
169 global \${$this->variableName};
171 \${$this->variableName} {$op} array(
180 * Ensure that Unix-style path separators ("/") are used in the path.
182 * @param string $path
185 protected static function normalizePathSeparator( $path ) {
186 return str_replace( '\\', '/', $path );
191 * Reads PHP code and returns the FQCN of every class defined within it.
193 class ClassCollector
{
196 * @var string Current namespace
198 protected $namespace = '';
201 * @var array List of FQCN detected in this pass
206 * @var array Token from token_get_all() that started an expect sequence
208 protected $startToken;
211 * @var array List of tokens that are members of the current expect sequence
216 * @var string $code PHP code (including <?php) to detect class names from
217 * @return array List of FQCN detected within the tokens
219 public function getClasses( $code ) {
220 $this->namespace = '';
221 $this->classes
= array();
222 $this->startToken
= null;
223 $this->tokens
= array();
225 foreach ( token_get_all( $code ) as $token ) {
226 if ( $this->startToken
=== null ) {
227 $this->tryBeginExpect( $token );
229 $this->tryEndExpect( $token );
233 return $this->classes
;
237 * Determine if $token begins the next expect sequence.
239 * @param array $token
241 protected function tryBeginExpect( $token ) {
242 if ( is_string( $token ) ) {
245 switch ( $token[0] ) {
249 $this->startToken
= $token;
254 * Accepts the next token in an expect sequence
258 protected function tryEndExpect( $token ) {
259 switch ( $this->startToken
[0] ) {
261 if ( $token === ';' ||
$token === '{' ) {
262 $this->namespace = $this->implodeTokens() . '\\';
264 $this->tokens
[] = $token;
270 $this->tokens
[] = $token;
271 if ( is_array( $token ) && $token[0] === T_STRING
) {
272 $this->classes
[] = $this->namespace . $this->implodeTokens();
278 * Returns the string representation of the tokens within the
279 * current expect sequence and resets the sequence.
283 protected function implodeTokens() {
285 foreach ( $this->tokens
as $token ) {
286 $content[] = is_string( $token ) ?
$token : $token[1];
289 $this->tokens
= array();
290 $this->startToken
= null;
292 return trim( implode( '', $content ), " \n\t" );