1
0
mirror of synced 2025-01-06 00:57:10 +03:00

Merge pull request #375 from lstrojny/transactional-callable

Allow passing any callable instead of only closures
This commit is contained in:
Benjamin Eberlei 2012-06-18 07:25:16 -07:00
commit 3aee619fc0
2 changed files with 26 additions and 5 deletions

View File

@ -19,7 +19,7 @@
namespace Doctrine\ORM; namespace Doctrine\ORM;
use Closure, Exception, use Exception,
Doctrine\Common\EventManager, Doctrine\Common\EventManager,
Doctrine\Common\Persistence\ObjectManager, Doctrine\Common\Persistence\ObjectManager,
Doctrine\DBAL\Connection, Doctrine\DBAL\Connection,
@ -210,15 +210,19 @@ class EntityManager implements ObjectManager
* If an exception occurs during execution of the function or flushing or transaction commit, * If an exception occurs during execution of the function or flushing or transaction commit,
* the transaction is rolled back, the EntityManager closed and the exception re-thrown. * the transaction is rolled back, the EntityManager closed and the exception re-thrown.
* *
* @param Closure $func The function to execute transactionally. * @param callable $func The function to execute transactionally.
* @return mixed Returns the non-empty value returned from the closure or true instead * @return mixed Returns the non-empty value returned from the closure or true instead
*/ */
public function transactional(Closure $func) public function transactional($func)
{ {
if (!is_callable($func)) {
throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
}
$this->conn->beginTransaction(); $this->conn->beginTransaction();
try { try {
$return = $func($this); $return = call_user_func($func, $this);
$this->flush(); $this->flush();
$this->conn->commit(); $this->conn->commit();

View File

@ -155,4 +155,21 @@ class EntityManagerTest extends \Doctrine\Tests\OrmTestCase
$this->assertEquals('foo', $return); $this->assertEquals('foo', $return);
} }
}
public function testTransactionalAcceptsVariousCallables()
{
$this->assertSame('callback', $this->_em->transactional(array($this, 'transactionalCallback')));
}
public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePassed()
{
$this->setExpectedException('InvalidArgumentException', 'Expected argument of type "callable", got "object"');
$this->_em->transactional($this);
}
public function transactionalCallback($em)
{
$this->assertSame($this->_em, $em);
return 'callback';
}
}