Skip to content

Commit

Permalink
autodiscover resources
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgergo committed Nov 22, 2024
1 parent 291113e commit a9428a5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
38 changes: 38 additions & 0 deletions src/Resources/Resources.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
4 changes: 3 additions & 1 deletion src/Root.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Root
*
* @var string
*/
public const VERSION = '2.5.1';
public const VERSION = '2.5.2';

/**
* The registered booting callbacks.
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit a9428a5

Please sign in to comment.