griffin/harpy

Search for Classes Names inside PHP Source Code

1.0.2 2021-05-11 16:23 UTC

This package is auto-updated.

Last update: 2024-10-11 23:43:34 UTC


README

Search for Classes Names inside PHP Source Code

Build Status Latest Stable Version Codecov License

Description

Harpy is a micro library to search for classes names inside PHP source code, using patterns to find files and parsing them to retrieve all defined classes.

This library is part of Griffin Project.

Installation

This package uses Composer as default repository. You can install it adding the name of package in require section of composer.json, pointing to the latest stable version.

{
  "require": {
    "griffin/harpy": "^1.0"
  }
}

Usage

The Griffin\Harpy\Harpy::search method use variadic parameters of string representing files or directories. These directories will be recursively listed searching for files. Each file found will be parsed searching for class definitions.

use Griffin\Harpy\Harpy;

$harpy = new Harpy();

$classnames = $harpy->search(
    // Files
    './src/Harpy.php',
    './tests/HarpyTest.php',
    // Directories
    './src',
    './tests',
);

var_dump($classnames);

/*
array(6) {
  [0]=>
  string(19) "Griffin\Harpy\Harpy"
  [1]=>
  string(27) "GriffinTest\Harpy\HarpyTest"
  [2]=>
  string(20) "Griffin\Harpy\Finder"
  [3]=>
  string(20) "Griffin\Harpy\Parser"
  [4]=>
  string(28) "GriffinTest\Harpy\FinderTest"
  [5]=>
  string(28) "GriffinTest\Harpy\ParserTest"
}
 */

If Harpy hasn't permissions to list directories or read files, warnings will not be raised, because it only searches for classes and not handles errors. Also, Harpy is not a class loader, you must use tools like Composer to execute this job.

Example

An example is retrieve all classes from directory and initialize a object if class implements specific interface.

use FooBar\ExampleInterface;
use Griffin\Harpy\Harpy;

$objects    = [];
$classnames = (new Harpy())->search('src');

foreach ($classnames as $classname) {
    if (is_subclass_of($classname, ExampleInterface::class, true /* allow string */)) {
        $objects[] = new $classname();
    }
}

Development

You can use Docker Compose to build an image and run a container to develop and test this package.

docker-compose build
docker-compose run --rm php composer install
docker-compose run --rm php composer test

References

License

This package is opensource and available under MIT license described in LICENSE.