Wire Doctrine's default connection to the tenant database resolved from the subdomain for HTTP requests and tenant-scoped Messenger messages while keeping master-only services on the master connection. This removes the production inconsistency where demo data, migrations and tenant commands used the tenant database but the web runtime still read from master.
47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Shared\Infrastructure\Tenant;
|
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent;
|
|
use Symfony\Component\HttpKernel\KernelEvents;
|
|
|
|
final readonly class TenantDatabaseRequestSubscriber implements EventSubscriberInterface
|
|
{
|
|
public function __construct(
|
|
private TenantDatabaseSwitcher $databaseSwitcher,
|
|
) {
|
|
}
|
|
|
|
public static function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
KernelEvents::REQUEST => ['onKernelRequest', 255],
|
|
KernelEvents::TERMINATE => 'onKernelTerminate',
|
|
];
|
|
}
|
|
|
|
public function onKernelRequest(RequestEvent $event): void
|
|
{
|
|
if (!$event->isMainRequest()) {
|
|
return;
|
|
}
|
|
|
|
$tenant = $event->getRequest()->attributes->get('_tenant');
|
|
if (!$tenant instanceof TenantConfig) {
|
|
$this->databaseSwitcher->useDefaultDatabase();
|
|
|
|
return;
|
|
}
|
|
|
|
$this->databaseSwitcher->useTenantDatabase($tenant->databaseUrl);
|
|
}
|
|
|
|
public function onKernelTerminate(): void
|
|
{
|
|
$this->databaseSwitcher->useDefaultDatabase();
|
|
}
|
|
}
|