Skip to content

Commit

Permalink
Add guard clause
Browse files Browse the repository at this point in the history
It maybe happen that the SQL COMMIT statement is successful, but then
something goes wrong. In that kind of case, you do not want to attempt a
rollback.

This was implemented in UnitOfWork::commit(), but for some reason not in
the similar EntityManager methods.
  • Loading branch information
greg0ire committed Oct 10, 2024
1 parent 51be1b1 commit b6137c8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/EntityManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,9 @@ public function transactional($func)
} finally {
if (! $successful) {
$this->close();
$this->conn->rollBack();
if ($this->conn->isTransactionActive()) {
$this->conn->rollBack();
}
}
}
}
Expand All @@ -285,7 +287,9 @@ public function wrapInTransaction(callable $func)
} finally {
if (! $successful) {
$this->close();
$this->conn->rollBack();
if ($this->conn->isTransactionActive()) {
$this->conn->rollBack();
}
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions tests/Tests/ORM/EntityManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Exception;
use Generator;
use InvalidArgumentException;
use PHPUnit\Framework\Assert;
use stdClass;
use TypeError;

Expand Down Expand Up @@ -409,6 +410,33 @@ public function rollBack(): bool
}
}

/** @dataProvider entityManagerMethodNames */
public function testItDoesNotAttemptToRollbackIfNoTransactionIsActive(string $methodName): void
{
$entityManager = new EntityManagerMock(
new class extends ConnectionMock {
public function commit(): bool
{
throw new Exception('Commit exception that happens after doing the actual commit');
}

public function rollBack(): bool
{
Assert::fail('Should not attempt to rollback if no transaction is active');
}

public function isTransactionActive(): bool
{
return false;
}
}
);

$this->expectExceptionMessage('Commit exception');
$entityManager->$methodName(static function (): void {
});
}

/** @return Generator<string, array{string}> */
public function entityManagerMethodNames(): Generator
{
Expand Down

0 comments on commit b6137c8

Please sign in to comment.