-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbIsolationExtension.php
More file actions
79 lines (69 loc) · 2.59 KB
/
DbIsolationExtension.php
File metadata and controls
79 lines (69 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
namespace Oro\Component\Testing;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Event\ConnectionEventArgs;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Oro\Component\Testing\Doctrine\Events;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
/**
* Provides functions to operate DB transactions.
*/
trait DbIsolationExtension
{
/**
* @var Connection[]
*/
protected static $dbIsolationConnections = [];
/**
* @internal
*/
protected function startTransaction(bool $nestTransactionsWithSavepoints = false)
{
if (false == $this->getClientInstance() instanceof KernelBrowser) {
throw new \LogicException('The client must be instance of KernelBrowser');
}
if (false == $this->getClientInstance()->getContainer()) {
throw new \LogicException('The client missing a container. Make sure the kernel was booted');
}
/** @var ManagerRegistry $registry */
$registry = $this->getClientInstance()->getContainer()->get('doctrine');
foreach ($registry->getManagers() as $em) {
if ($em instanceof EntityManagerInterface) {
$objectId = spl_object_id($em->getConnection());
if (array_key_exists($objectId, self::$dbIsolationConnections)) {
continue;
}
$em->clear();
$connection = $em->getConnection();
if ($connection->getNestTransactionsWithSavepoints() !== $nestTransactionsWithSavepoints) {
$connection->setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints);
}
$connection->beginTransaction();
self::$dbIsolationConnections[$objectId] = $connection;
}
}
}
/**
* @internal
*/
protected static function rollbackTransaction()
{
foreach (array_reverse(self::$dbIsolationConnections) as $connection) {
$rolledBack = false;
while ($connection->isConnected() && $connection->isTransactionActive()) {
$connection->rollBack();
$rolledBack = true;
}
if ($rolledBack) {
$args = new ConnectionEventArgs($connection);
$connection->getEventManager()->dispatchEvent(Events::ON_AFTER_TEST_TRANSACTION_ROLLBACK, $args);
}
}
self::$dbIsolationConnections = [];
}
/**
* @return \Symfony\Bundle\FrameworkBundle\KernelBrowser
*/
abstract protected static function getClientInstance();
}