routes/src/Console/InstallCommand.php

69 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace Jltx\Routes\Console;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'jltx:routes:install')]
class InstallCommand
{
/**
* The name and signature of the console command.
*/
protected string $signature = 'jltx:routes:install';
/**
* The console command description.
*/
protected string $description = '安装路由包资源';
/**
* Execute the console command.
*/
public function handle(): void
{
$this->components->info('Installing Routes resources.');
collect([
'Service Provider' => fn () => $this->callSilent('vendor:publish', ['--tag' => 'routes-provider']) == 0,
'Configuration' => fn () => $this->callSilent('vendor:publish', ['--tag' => 'routes-config']) == 0,
])->each(fn ($task, $description) => $this->components->task($description, $task));
$this->registerRouteServiceProvider();
$this->components->info('Jltx Routes scaffolding installed successfully.');
}
/**
* Register the Horizon service provider in the application configuration file.
*/
protected function registerRouteServiceProvider(): void
{
$namespace = Str::replaceLast('\\', '', $this->laravel->getNamespace());
if (file_exists($this->laravel->bootstrapPath('providers.php'))) {
ServiceProvider::addProviderToBootstrapFile("$namespace\\Providers\\RouteServiceProvider");
} else {
$appConfig = file_get_contents(config_path('app.php'));
if (Str::contains($appConfig, $namespace.'\\Providers\\RouteServiceProvider::class')) {
return;
}
file_put_contents(config_path('app.php'), str_replace(
"{$namespace}\\Providers\EventServiceProvider::class,".PHP_EOL,
"{$namespace}\\Providers\EventServiceProvider::class,".PHP_EOL." {$namespace}\Providers\RouteServiceProvider::class,".PHP_EOL,
$appConfig
));
}
file_put_contents(app_path('Providers/RouteServiceProvider.php'), str_replace(
"namespace App\Providers;",
"namespace {$namespace}\Providers;",
file_get_contents(app_path('Providers/RouteServiceProvider.php'))
));
}
}