|
| 1 | +# ClassFileLocator |
| 2 | + |
| 3 | +`Zend\File\ClassFileLocator` is a PHP [FilterIterator](http://php.net/FilterIterator) |
| 4 | +for use with locating files containing PHP classes, interfaces, abstracts, or |
| 5 | +traits. As such, it should be used in conjunction with a |
| 6 | +[DirectoryIterator](http://php.net/DirectoryIterator) or |
| 7 | +[RecursiveDirectoryIterator](http://php.net/RecursiveDirectoryIterator). |
| 8 | + |
| 9 | +Use cases include building class maps for autoloading. |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +The `ClassFileLocator` constructor can take one of: |
| 14 | + |
| 15 | +- a string representing a directory location; if valid, this will be used to |
| 16 | + seed a `RecursiveDirectoryIterator` instance. |
| 17 | +- a `DirectoryIterator` instance. |
| 18 | +- a `RecursiveDirectoryIterator` instance. |
| 19 | + |
| 20 | +In each case, once constructed, iteration will result in a list of files |
| 21 | +containing PHP clases, interfaces, abstracts, or traits. |
| 22 | + |
| 23 | +Instead of returning standard [SplFileInfo](http://php.net/SplFileInfo) |
| 24 | +instances, the `ClassFileLocator` is configured to cast to |
| 25 | +`Zend\File\PhpClassFile` instances, which extend `SplFileInfo`, and provide the |
| 26 | +following additional methods: |
| 27 | + |
| 28 | +- `getClasses()`: returns an array of all classes, abstract classes, interfaces, |
| 29 | + and traits defined in the file; all names are fully qualified. |
| 30 | +- `getNamespaces()`: returns an array of namespaces defined in the file. |
| 31 | + |
| 32 | +> ### Tokenization |
| 33 | +> |
| 34 | +> The `ClassFileLocator` uses the [tokenizer](http://php.net/tokenizer) |
| 35 | +> extension in order to locate items of interest; as such, its operations |
| 36 | +> will not execute PHP files it finds. |
| 37 | +
|
| 38 | +## Example |
| 39 | + |
| 40 | +The following will spit out a PHP file that returns a class map for the `src/` |
| 41 | +directory in which it is run: |
| 42 | + |
| 43 | +```php |
| 44 | +<?php |
| 45 | +use Zend\File\ClassFileLocator; |
| 46 | + |
| 47 | +$path = realpath(getcwd() . '/src'); |
| 48 | + |
| 49 | +$locator = new ClassFileLocator($path); |
| 50 | +$map = []; |
| 51 | + |
| 52 | +foreach ($locator as $file) { |
| 53 | + $filename = str_replace($path . '/', '', $file->getRealPath()); |
| 54 | + foreach ($file->getClasses() as $class) { |
| 55 | + $map[$class] = $filename; |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +printf("<?php\nreturn %s;", var_export($map, true)); |
| 60 | +``` |
0 commit comments