Skip to content

Commit

Permalink
Add module class support for tinker
Browse files Browse the repository at this point in the history
  • Loading branch information
inxilpro committed Jun 25, 2024
1 parent 76eebca commit 2ef17e4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Added support for auto-aliasing module classes in tinker sessions

## [2.2.0] - 2024-04-05

### Added

- The modules sync command now adds modules to PhpStorm exclude path, preventing double-registration of modules

## [2.1.0] - 2024-03-18

### Added

- Added support for Laravel 11
Expand Down
25 changes: 24 additions & 1 deletion src/Support/ModularServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
use Illuminate\Database\Eloquent\Factories\Factory as EloquentFactory;
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Translation\Translator;
Expand Down Expand Up @@ -68,7 +69,7 @@ public function register(): void
$this->registerLazily(Gate::class, [$this, 'registerPolicies']);

// Look for and register all our commands in the CLI context
Artisan::starting(Closure::fromCallable([$this, 'registerCommands']));
Artisan::starting(Closure::fromCallable([$this, 'onArtisanStart']));
}

public function boot(): void
Expand Down Expand Up @@ -275,6 +276,12 @@ protected function registerPolicies(Gate $gate): void
});
}

protected function onArtisanStart(Artisan $artisan): void
{
$this->registerCommands($artisan);
$this->registerNamespacesInTinker();
}

protected function registerCommands(Artisan $artisan): void
{
$this->autoDiscoveryHelper()
Expand All @@ -288,6 +295,22 @@ protected function registerCommands(Artisan $artisan): void
});
}

protected function registerNamespacesInTinker()
{
if (! class_exists('Laravel\\Tinker\\TinkerServiceProvider')) {
return;
}

$namespaces = app(ModuleRegistry::class)
->modules()
->flatMap(fn(ModuleConfig $config) => $config->namespaces)
->reject(fn($ns) => Str::endsWith($ns, ['Tests\\', 'Database\\Factories\\', 'Database\\Seeders\\']))
->values()
->all();

Config::set('tinker.alias', array_merge($namespaces, Config::get('tinker.alias', [])));
}

protected function registerLazily(string $class_name, callable $callback): self
{
$this->app->resolving($class_name, Closure::fromCallable($callback));
Expand Down

0 comments on commit 2ef17e4

Please sign in to comment.