/class-finder

Utility class to help you discover other classes / namespaces based on the composer auto loader.

Primary LanguagePHPMIT LicenseMIT

Class Finder, like Symfony\Finder but for classes.

Build Status Latest Stable Version Total Downloads License Coverage Status Scrutinizer Code Quality

Utility class to help you discover other classes / namespaces based on the composer auto loader.

How to Install

Installation via composer is easy:

composer require gears/class-finder

Examples

// Make sure you grab the composer ClassLoader instance, the class finder needs it.
$composer = require('vendor/autoload.php');

// Create a new finder. You may reuse this as much as you like.
// Right now caching is not performed but could be in the future.
$finder = new Gears\ClassFinder($composer);

// Find all classes inside a namespace
$classes = $finder->namespace('Foo\\Bar')->search();

// Returns an array like:
$classes =
[
    '/home/user/project/vendor/foo/src/Bar/Baz.php' => 'Foo\\Bar\\Baz',
    '/home/user/project/vendor/foo/src/Bar/Qux.php' => 'Foo\\Bar\\Qux',
    'etc...'
];

// Find all classes inside a namespace that implement an interface.
$classes = $finder->namespace('Foo\\Bar')->implements('SomeInterface')->search();

// OR you can use the PHP 5.5 ::class operator
$classes = $finder->namespace('Foo\\Bar')->implements(SomeInterface::class)->search();

// Or filter by parent classes
$classes = $finder->namespace('Foo\\Bar')->extends(SomeParent::class)->search();

// NOTE: You can't do both out of the box.
$classes = $finder->namespace('Foo\\Bar')

// This is now allowed!
->implements(SomeInterface::class)
->extends(SomeParent::class)

->search();

// Although you could supply your own custom filter that implemented whatever filtering you like.
$classes = $finder->namespace('Foo\\Bar')->filterBy(function($rClass ReflectionClass)
{
    
    /* custom logic goes here, must return true or false */
    
})->search();

// ClassFinder also implements the IteratorAggregate & Countable interfaces.
$number = $finder->namespace('Foo\\Bar')->count();

foreach ($finder->namespace('Foo\\Bar') as $filepath => $fqcn)
{
    
}

Developed by Brad Jones - brad@bjc.id.au