attributes->has($middlewareKey)) { Log::warning('DomainSessionSync: Middleware bereits ausgeführt - Skip um Cookie-Duplikate zu vermeiden', [ 'request_id' => $request->header('X-Request-ID') ?? uniqid(), 'url' => $request->getUri() ]); return $next($request); } // Markieren dass diese Middleware läuft $request->attributes->set($middlewareKey, true); try { // Domain-Context aus Container holen /** @var DomainContext|null $context */ $context = app(DomainContext::class); // Session-Synchronisation VOR Controller (Fix: Timing-Problem) if ($context && $this->shouldSync($context)) { $this->sessionManager->synchronize($request, $context); } } catch (\Throwable $e) { // Kritisch: Session-Sync-Fehler dürfen Response nicht stoppen Log::error('Session synchronization failed', [ 'error' => $e->getMessage(), 'host' => $request->getHost(), 'path' => $request->path(), 'user_agent' => $request->userAgent(), 'fallback' => 'continuing_without_sync' ]); } // Controller läuft NACH Session-Sync und kann synchronisierte Daten nutzen $response = $next($request); // Optional: Nur Cleanup/Logging nach Response try { $context = app(DomainContext::class); if ($context) { $this->logSessionSync($context); } } catch (\Throwable $e) { // Logging-Fehler ignorieren } return $response; } /** * Prüft, ob Session-Sync benötigt wird (Performance-Optimierung) */ private function shouldSync(DomainContext $context): bool { // Skip für unbekannte Domains (keine Session-Daten nötig) if ($context->type === 'unknown') { return false; } // Skip für Hauptdomain ohne UserShop-Kontext if ($context->type === 'main' && !$context->userShop) { return false; } return true; } /** * Minimal Debug-Logging (nur bei aktivierter Debug-Konfiguration) */ private function logSessionSync(DomainContext $context): void { if (!config('subdomain.debug.log_domain_switches', false)) { return; } Log::debug('Session synchronized', [ 'domain_type' => $context->type ?? 'unknown', 'user_shop_slug' => $context->userShop?->slug, 'session_id' => session()->getId(), 'memory_usage_mb' => round(memory_get_usage() / 1024 / 1024, 2) ]); } }