{"id":19325089,"url":"https://github.com/spatie/php-structure-discoverer","last_synced_at":"2025-04-04T16:13:49.535Z","repository":{"id":57711495,"uuid":"420093058","full_name":"spatie/php-structure-discoverer","owner":"spatie","description":"Automatically discover classes within your PHP application","archived":false,"fork":false,"pushed_at":"2024-03-13T16:10:07.000Z","size":212,"stargazers_count":105,"open_issues_count":0,"forks_count":9,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-05-01T11:46:09.696Z","etag":null,"topics":["discover","laravel","php"],"latest_commit_sha":null,"homepage":"https://spatie.be/open-source","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"LaravelAutoDiscoverer"}},"created_at":"2021-10-22T12:37:54.000Z","updated_at":"2024-06-19T09:54:20.070Z","dependencies_parsed_at":"2024-06-19T09:54:11.435Z","dependency_job_id":"1c760933-074a-44bf-aefa-050708049f02","html_url":"https://github.com/spatie/php-structure-discoverer","commit_stats":{"total_commits":77,"total_committers":7,"mean_commits":11.0,"dds":"0.49350649350649356","last_synced_commit":"90e9bb1f9c1a5dd19d482bcf13959b0e9451fb1d"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":"spatie/package-skeleton-laravel","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fphp-structure-discoverer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fphp-structure-discoverer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fphp-structure-discoverer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Fphp-structure-discoverer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/php-structure-discoverer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247208141,"owners_count":20901570,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["discover","laravel","php"],"created_at":"2024-11-10T02:08:50.780Z","updated_at":"2025-04-04T16:13:49.515Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/LaravelAutoDiscoverer"],"categories":[],"sub_categories":[],"readme":"# Automatically discover classes, interfaces, enums, and traits within your PHP application\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/php-structure-discoverer.svg?style=flat-square)](https://packagist.org/packages/spatie/php-structure-discoverer)\n[![run-tests](https://github.com/spatie/php-structure-discoverer/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/run-tests.yml)\n[![PHPStan](https://github.com/spatie/php-structure-discoverer/actions/workflows/phpstan.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/phpstan.yml)\n[![Check \u0026 fix styling](https://github.com/spatie/php-structure-discoverer/actions/workflows/php-cs-fixer.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/php-cs-fixer.yml)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/php-structure-discoverer.svg?style=flat-square)](https://packagist.org/packages/spatie/php-structure-discoverer)\n\nWith this package, you'll be able to discover structures in your PHP application that fulfill certain conditions quickly. For example, you could search for classes implementing an interface:\n\n```php\nuse Spatie\\StructureDiscoverer\\Discover;\n\n// PostModel::class, Collection::class, ...\nDiscover::in(__DIR__)-\u003eclasses()-\u003eimplementing(Arrayable::class)-\u003eget(); \n```\n\nAs an added benefit, it has a built-in cache functionality that makes the whole process fast in production.\n\nThe package is not only limited to classes but can also find enums, interfaces, and traits and has extra metadata for each structure.\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/php-structure-discoverer.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/php-structure-discoverer)\n\nWe invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can\nsupport us by [buying one of our paid products](https://spatie.be/open-source/support-us).\n\nWe highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.\nYou'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards\non [our virtual postcard wall](https://spatie.be/open-source/postcards).\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/php-structure-discoverer\n```\n\nIf you're using Laravel, then you can also publish the config file with the following command:\n\n```bash\nphp artisan vendor:publish --tag=\"structure-discoverer-config\"\n```\n\nThis is the contents of the published config file:\n\n```php\nreturn [\n    /*\n     *  A list of files that should be ignored during the discovering process.\n     */\n    'ignored_files' =\u003e [\n\n    ],\n\n    /**\n     * The directories where the package should search for structure scouts\n     */\n    'structure_scout_directories' =\u003e [\n        app_path(),\n    ],\n\n    /*\n     *  Configure the cache driver for discoverers\n     */\n    'cache' =\u003e [\n        'driver' =\u003e \\Spatie\\StructureDiscoverer\\Cache\\LaravelDiscoverCacheDriver::class,\n        'store' =\u003e null,\n    ]\n];\n```\n\n## Usage\n\nYou always need to define in which directories you want to look for structures:\n\n```php\nDiscover::in(__DIR__)-\u003e...\n```\n\nIt is possible to look in multiple directories like this:\n\n```php\nDiscover::in(app_path('models'), app_path('enums'))-\u003e...\n```\n\nYou can get the structures as such:\n\n```php\nDiscover::in(__DIR__)-\u003eget();\n```\n\nWhich will return an array of class FCQN, and because no conditions were added, the package will return all classes, enums, interfaces, and traits.\n\nYou only discover classes like this:\n\n```php\nDiscover::in(__DIR__)-\u003eclasses()-\u003eget();\n```\n\nInterfaces like this:\n\n```php\nDiscover::in(__DIR__)-\u003einterfaces()-\u003eget();\n```\n\nEnums like this:\n\n```php\nDiscover::in(__DIR__)-\u003eenums()-\u003eget();\n```\n\nAnd traits like this:\n\n```php\nDiscover::in(__DIR__)-\u003etraits()-\u003eget();\n```\n\nWhen you want to include a specific named structure, you can do the following:\n\n```php\nDiscover::in(__DIR__)-\u003enamed('MyAwesomeClass')-\u003eget();\n```\n\nYou can discover classes extending another class as such:\n\n```php\nDiscover::in(__DIR__)-\u003eextending(Model::class)-\u003eget();\n```\n\nDiscovering classes, interfaces, or enums implementing an interface can be done like this:\n\n```php\nDiscover::in(__DIR__)-\u003eimplementing(Arrayable::class)-\u003eget();\n```\n\nBe aware that although interfaces extend another interface, in this context, the implements keyword seemed a more logical choice to find interfaces extended by another interface. Using the `extends` method for such a filter won't work!\n\nClasses, interfaces, or traits using an attribute can be discovered as such:\n\n```php\nDiscover::in(__DIR__)-\u003ewithAttribute(Cast::class)-\u003eget();\n```\n\nFor more fine-grained control, you can use a closure that receives a `DiscoveredStructure` object (more on that later) and should return `true` if the structure should be included:\n\n ```php\nDiscover::in(__DIR__)\n    -\u003ecustom(fn(DiscoveredStructure $structure) =\u003e $structure-\u003enamespace === 'App')\n    -\u003eget()\n```\n\nMore complex custom conditions can be embedded in a class:\n\n```php\nclass AppDiscoverCondition extends DiscoverCondition \n{\n    public function satisfies(DiscoveredStructure $discoveredData): bool\n    {\n        return $structure-\u003enamespace === 'App';\n    }\n};\n```\n\nThis condition can now be used like this:\n\n ```php\nDiscover::in(__DIR__)\n    -\u003ecustom(new AppDiscoverCondition())\n    -\u003eget()\n```\n\n### Combining conditions\n\nBy default, all conditions will work like an AND operation, so in this case:\n\n```php\nDiscover::in(__DIR__)-\u003eclasses()-\u003eimplementing(Arrayable::class)-\u003eget();\n```\n\nThe package will only look for structures that are a class **and** implement `Arrayble`.\n\nYou can create an OR combination of conditions like this:\n\n```php\nDiscover::in(__DIR__)\n    -\u003eany(\n        ConditionBuilder::create()-\u003eclasses(),\n        ConditionBuilder::create()-\u003eenums()\n    )\n    -\u003eget();\n```\n\nNow, the package will only discover classes **or** enum structures.\n\nYou can also create more complex operations like an or of and's:\n\n```php\nDiscover::in(__DIR__)\n    -\u003eany(\n        ConditionBuilder::create()-\u003eexact(\n            ConditionBuilder::create()-\u003eclasses(),\n            ConditionBuilder::create()-\u003eimplementing(Arrayble::class),\n        ),\n        ConditionBuilder::create()-\u003eexact(\n            ConditionBuilder::create()-\u003eenums(),\n            ConditionBuilder::create()-\u003eimplementing(Stringable::class),\n        )\n    )\n    -\u003eget();\n```\n\nThis example can be written shorter like this:\n\n```php\nDiscover::in(__DIR__)\n    -\u003eany(\n        ConditionBuilder::create()-\u003eexact(\n            ConditionBuilder::create()-\u003eclasses()-\u003eimplementing(Arrayble::class),\n        ),\n        ConditionBuilder::create()-\u003eexact(\n            ConditionBuilder::create()-\u003eenums()-\u003eimplementing(Stringable::class),\n        )\n    )\n    -\u003eget();\n```\n\n### Sorting\n\nBy default, the discovered structures will be sorted according to the OS' default.\n\nYou can change the sorting like this:\n\n```php\nuse Spatie\\StructureDiscoverer\\Enums\\Sort;\n\nDiscover::in(__DIR__)-\u003esortBy(Sort::Name)-\u003eget();\n```\n\nHere are all the available sorting options:\n\n```php\nuse Spatie\\StructureDiscoverer\\Enums\\Sort;\n\nDiscover::in(__DIR__)-\u003esortBy(Sort::Name);\nDiscover::in(__DIR__)-\u003esortBy(Sort::Size);\nDiscover::in(__DIR__)-\u003esortBy(Sort::Type);\nDiscover::in(__DIR__)-\u003esortBy(Sort::Extension);\nDiscover::in(__DIR__)-\u003esortBy(Sort::ChangedTime);\nDiscover::in(__DIR__)-\u003esortBy(Sort::ModifiedTime);\nDiscover::in(__DIR__)-\u003esortBy(Sort::AccessedTime);\nDiscover::in(__DIR__)-\u003esortBy(Sort::CaseInsensitiveName);\n```\n\n### Caching\n\nThis package can cache all discovered structures, so no performance-heavy operations are required in production.\n\nThe fastest way to start caching is by creating a structure scout, which is a class that describes what you want to discover:\n\n```php\nclass EnumsStructureScout extends StructureScout\n{\n    protected function definition(): Discover|DiscoverConditionFactory\n    {\n        return Discover::in(__DIR__)-\u003eenums();\n    }\n\n    public function cacheDriver(): DiscoverCacheDriver\n    {\n        return new FileDiscoverCacheDriver('/path/to/temp/directory');\n    }\n}\n```\n\nEach structure scout extends from `StructureScout` and should have\n\n- a definition where you describe what to discover and where. Just like we did inline earlier\n- a driver to be used for the cache. When you're using Laravel, this method is not required since it is already defined in the config file\n\nWithin your application, you can use the discoverer as such:\n\n```php\nEnumsStructureScout::create()-\u003eget();\n```\n\nThe first time this method is called, the whole discovery process will run taking a bit more time. The second call will skip the discovery process and use the cached version, making a call to this method amazingly fast!\n\n#### In production\n\nWhen you're deploying to production, you can warm all your structure scout caches as such:\n\n```php\nStructureScoutManager::cache([__DIR__]); \n```\n\nYou should provide a directory where the structure scouts are stored.\n\nIf you're using Laravel, you can run the following command:``\n\n````bash\nphp artisan structure-scouts:cache\n````\n\nIt is also possible to clear all caches for structure scouts as such:\n\n```php\nStructureScoutManager::clear([__DIR__]); \n```\n\nOr, if you're using Laravel:\n\n````bash\nphp artisan structure-scouts:clear\n````\n\n##### For packages\n\nSince an individual user defines the directories where structure scouts can be found, packages can't ensure their structure scouts will be discovered with the cache commands.\n\nIt is possible to add structure scouts like this manually:\n\n```php\nStructureScoutManager::add(SettingsStructureScout::class); \n```\n\nIn a Laravel application, you typically do this within the package ServiceProvider.\n\n#### Cache drivers\n\n##### File\n\nThe `FileDiscoverCacheDriver` allows you to cache discovered structures in a file. You should provide a `directory` parameter where all the cache files should be stored.\n\n##### Laravel\n\nThe `LaravelDiscoverCacheDriver` will use the default Laravel cache. You can provide an optional `store` parameter to define the store to be used and an optional `prefix` parameter for the cache key.\n\n##### Null\n\nThe `NullDiscoverCacheDriver` will not cache anything and can be used for testing purposes.\n\n##### Your own\n\nA cache driver can be built by extending the `DiscoverCacheDriver` interface:\n\n```php\ninterface DiscoverCacheDriver\n{\n    public function has(string $id): bool;\n\n    public function get(string $id): array;\n\n    public function put(string $id, array $discovered): void;\n\n    public function forget(string $id): void;\n}\n```\n\n#### Without structure scouts\n\nYou can also use caching inline without the use of scouts, be aware warming up these caches in production is not possible:\n\n```php\nDiscover::in(__DIR__)\n   -\u003ewithCache(\n      'Some identifier',\n      new FileDiscoverCacheDriver('/path/to/temp/directory);\n   )\n    -\u003eget();\n```\n\n### Parallel\n\nGetting all structures in a bigger application can be slow due to many files being scanned. This process can be sped up by parallelized scanning. You can enable this as such:\n\n```php\nDiscover::in(__DIR__)-\u003eparallel()-\u003eget();\n```\n\nIt is possible to set the number of files each process will scan:\n\n```php\nDiscover::in(__DIR__)-\u003eparallel(100)-\u003eget();\n```\n\nBy default, each process will scan 50 files.\n\n### Chains\n\nOften structures inherit other structures with extends and implementations. The package automatically includes these structures when discovering them. So for example\n\n```php\nclass Request\n{\n}\n\nclass FormRequest extends Request\n{\n}\n\nclass UserFormRequest extends FormRequest\n{\n}\n```\n\nWhen using:\n\n```php\nDiscover::in(__DIR__)-\u003eextending(Request::class)-\u003eget();\n```\n\nBoth `FormRequest` and `UserFormRequest` will be found, and although `UserFormRequest` is not a direct descendant of `Request`, it is one through `FormRequest`.\n\nYou can disable this behavior for extending as such:\n\n```php\nDiscover::in(__DIR__)-\u003eextendingWithoutChain(Request::class)\n```\n\nOr for implementing as such:\n\n```php\nDiscover::in(__DIR__)-\u003eimplementingWithoutChain(Request::class)\n```\n\nResolving chains is a complicated and resource-heavy process. It can be completely disabled as such:\n\n```php\nDiscover::in(__DIR__)-\u003ewithoutChains()-\u003eextending(Request::class)-\u003eget();\n```\n\n### Full information\n\nThe output will be a reference string to the structure when discovering structures. Internally the package keeps track of a lot more information which can be helpful for all purposes. You can also retrieve this information as such:\n\n```php\nDiscover::in(__DIR__)-\u003efull()-\u003eget();\n```\n\nInstead of returning an array of strings, now an array of `DiscoveredStructure` objects is returned. Let's go through the different types:\n\n#### DiscoveredClass\n\nRepresents a class, the `$extends` and `$implements` properties address the direct extend and implements of the class. The `$extendsChain` and `$implementsChain` properties contain all extends and implements for the complete inheritance chain.\n\n```php\nclass DiscoveredClass extends DiscoveredStructure\n{\n    public function __construct(\n        string $name,\n        string $file,\n        string $namespace,\n        public bool $isFinal,\n        public bool $isAbstract,\n        public bool $isReadonly,\n        public ?string $extends,\n        public array $implements,\n        public array $attributes,\n        public ?array $extendsChain = null,\n        public ?array $implementsChain = null,\n    ) {\n    }\n}\n```\n\n#### DiscoveredInterface\n\nRepresents a class, the `$extends` property addresses the direct extends of the interface. The `$extendsChain` property contains all extends for the whole inheritance chain.\n\n```php\nclass DiscoveredInterface extends DiscoveredStructure\n{\n    public function __construct(\n        string $name,\n        string $file,\n        string $namespace,\n        public array $extends,\n        public array $attributes,\n        public ?array $extendsChain = null,\n    ) {\n    }\n```\n\n#### DiscoveredEnum\n\nRepresents an enum, the `$implements` property addresses the direct extends of the enum. The `$implementsChain` property contains all implements for the full inheritance chain. The `$type` property is an enum describing the type: `Unit`, `String`, and `Int`.\n\n```php\nclass DiscoveredEnum extends DiscoveredStructure\n{\n    public function __construct(\n        public string $name,\n        public string $namespace,\n        public string $file,\n        public DiscoveredEnumType $type,\n        public array $implements,\n        public array $attributes,\n        public ?array $implementsChain = null,\n    ) {\n    }\n}\n```\n\n### DiscoveredTrait\n\nRepresents a discovered trait within the application.\n\n```php\nclass DiscoveredTrait extends DiscoveredStructure\n{\n    public function __construct(\n        public string $name,\n        public string $namespace,\n        public string $file,\n    ) {\n    }\n}\n```\n\n### Parsers\n\nThe parser is responsible for parsing a file and returning a list of structures. The package comes with two parsers out of the box:\n\n- `PhpTokenStructureParser`: Reads a PHP file, tokenizes it, and parses the tokens into structures.\n- `ReflectionStructureParser`: Uses the PHP reflection API to read a file and parse it into structures.\n\nBy default, the `PhpTokenStructureParser` is used due to it being more robust, the `ReflectionStructureParser` is quite a bit faster but can completely fail the PHP process.\n\nYou can enable the `ReflectionStructureParser` as such:\n\n```php\nDiscover::in(__DIR__)\n   -\u003euseReflection(\n      basePath: '/path/to/project/root',\n      rootNamespace: null\n   )\n   -\u003eget();\n```\n\nYou'll likely need to set the basePath to the root of your project, and optionally the root namespace of your project which will be prepended.\n\nFor default Laravel projects this would be:\n\n```php\nDiscover::in(__DIR__)\n   -\u003euseReflection(basePath: base_path())\n   -\u003eget();\n```\n\n### Help? My structure cannot be found!\n\nThe internals of this package will scan all files within a directory and try to make a virtual map linking all structures with their extends, uses, and implementations.\n\nDue to this file scanning, this map is incomplete if referenced structures are not being scanned.\n\nFor example, we scan for all classes extending Laravel's `Model` in our app directory, a lot of models have been found, but the `User` model is missing.\n\nThe reason why this is happening is that:\n\n- The package searches in the app directory for classes extending `Model`\n- `User` extends `Authenticatable`, which itself extends `Model`\n- `Authenticatable` is stored within the `vendor/laravel/...` directory, which isn't being scanned\n- The package does not know that `Authenticatable` extends `Model`\n- `User` will not be found\n\nA solution to this problem is to include the `laravel` directory in the scanning process.\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Ruben Van Assche](https://github.com/rubenvanassche)\n- [Construct Finder](https://github.com/thephpleague/construct-finder) a big influence for this package\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fphp-structure-discoverer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Fphp-structure-discoverer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Fphp-structure-discoverer/lists"}