From a9428a52c894a069319546564b8998df3c1db3bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=2E=20Nagy=20Gerg=C5=91?= Date: Fri, 22 Nov 2024 11:43:29 +0100 Subject: [PATCH] autodiscover resources --- src/Resources/Resources.php | 38 +++++++++++++++++++++++++++++++++++++ src/Root.php | 4 +++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/Resources/Resources.php b/src/Resources/Resources.php index aba72c9f..c30df0d6 100644 --- a/src/Resources/Resources.php +++ b/src/Resources/Resources.php @@ -7,9 +7,47 @@ use Illuminate\Http\Request; use Illuminate\Support\Arr; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\App; +use Illuminate\Support\Str; +use ReflectionClass; +use Symfony\Component\Finder\Finder; class Resources extends Collection { + /** + * Discover the resources in the given paths. + */ + public function discoverIn(string|array $paths): void + { + foreach ((array) $paths as $path) { + if (is_dir($path)) { + $this->discover($path); + } + } + } + + /** + * Discover and register the resources. + */ + protected function discover(string $path): void + { + $namespace = App::getNamespace(); + + foreach ((new Finder)->in($path)->files() as $resource) { + $resource = str_replace( + ['/', '.php'], + ['\\', ''], + Str::after($resource->getPathname(), App::path().DIRECTORY_SEPARATOR) + ); + + $resource = $namespace.$resource; + + if (is_subclass_of($resource, Resource::class) && (new ReflectionClass($resource))->isInstantiable()) { + $this->register(new $resource); + } + } + } + /** * Register the given resource into the collection. */ diff --git a/src/Root.php b/src/Root.php index 9cc48d96..2fe01604 100644 --- a/src/Root.php +++ b/src/Root.php @@ -24,7 +24,7 @@ class Root * * @var string */ - public const VERSION = '2.5.1'; + public const VERSION = '2.5.2'; /** * The registered booting callbacks. @@ -98,6 +98,8 @@ public static function instance(): static */ public function boot(): void { + $this->resources->discoverIn($this->app->path('Root/Resources')); + $this->resources->each->boot($this); foreach ($this->booting as $callback) {