<?php
namespace App\EventSubscriber;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class DatabaseSwitcherSubscriber implements EventSubscriberInterface
{
/**
* @var ManagerRegistry
*/
protected $doctrine;
/**
* DatabaseSwitcherSubscriber constructor.
*
* @param ManagerRegistry $registry
*/
public function __construct(ManagerRegistry $registry)
{
$this->doctrine = $registry;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 1000],
],
];
}
/**
* @throws \Doctrine\DBAL\DBALException
*/
public function onKernelRequest()
{
$testMode = getenv('TEST_MODE');
if ($testMode) {
/** @var Connection $connection */
$connection = $this->doctrine->getConnection();
/** @var Connection $testConnection */
$testConnection = $this->doctrine->getConnection('test');
if (!$connection->isConnected()) {
$connection->__construct(
$testConnection->getParams(),
$testConnection->getDriver(),
$testConnection->getConfiguration(),
$testConnection->getEventManager()
);
$connection->connect();
}
}
}
}