mivita/dev/routes-optimization/DomainServiceProvider.php
2025-10-20 17:42:08 +02:00

86 lines
3.3 KiB
PHP

<?php
namespace App\Providers;
use App\Domain\DomainContext;
use App\Http\Middleware\DomainResolver;
use App\Models\UserShop;
use App\Services\DomainService;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Support\ServiceProvider;
class DomainServiceProvider extends ServiceProvider
{
/**
* Registriert die Domain-Dienste im Service-Container.
*
* @return void
*/
public function register()
{
// 1. DomainService als Singleton registrieren.
// Er wird die Konfiguration `config/domains.php` verwenden.
$this->app->singleton(DomainService::class, function ($app) {
$domainService = new DomainService($app['config']['domains']);
// Validiere Konfiguration in der Development-Umgebung
if (config('app.debug')) {
$configErrors = $domainService->validateConfiguration();
if (!empty($configErrors)) {
\Log::channel('domain')->warning('Domain configuration errors detected', ['errors' => $configErrors]);
}
}
return $domainService;
});
// 2. DomainContext als Singleton registrieren.
// Die Logik hier wird nur einmal pro Anfrage ausgeführt, wenn der
// Context das erste Mal benötigt wird (z.B. in der Middleware).
$this->app->singleton(DomainContext::class, function ($app) {
/** @var DomainService $domainService */
$domainService = $app->make(DomainService::class);
$request = $app->make('request');
// Analysiere den Host der aktuellen Anfrage
$domainInfo = $domainService->parseDomain($request->getHost());
if (config('app.debug')) {
\Log::channel('domain')->debug('DomainServiceProvider: domainInfo', [
'domainInfo' => $domainInfo,
'host' => $request->getHost()
]);
}
$userShop = null;
// Wenn es sich um eine User-Shop-Domain handelt, versuche das Shop-Objekt zu finden.
if ($domainInfo['type'] === 'user-shop' && $domainInfo['subdomain']) {
$userShop = $domainService->getUserShop($domainInfo['subdomain']);
// Wenn der Shop ungültig ist, wird der Typ auf 'unknown' gesetzt.
if (!$userShop) {
$domainInfo['type'] = 'unknown';
}
}
// Wenn es sich um die Haupt-Shop-Domain handelt (z.B. mivita.shop),
// lade den konfigurierten Fallback-Shop.
if ($domainInfo['type'] === 'main-shop' && $domainInfo['default_user_shop']) {
$userShop = $domainService->getUserShop($domainInfo['default_user_shop']);
}
return DomainContext::fromArray($domainInfo, $userShop);
});
}
/**
* Führt Aktionen nach der Registrierung aller Provider aus.
*
* @return void
*/
public function boot(Kernel $kernel)
{
// Registriert die neue Middleware global für die 'web' Gruppe.
// Sie wird vor anderen Middleware ausgeführt, um den Kontext frühzeitig zu setzen.
$kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);
$kernel->prependMiddlewareToGroup('web', DomainResolver::class);
}
}