Skip to content

Instantly share code, notes, and snippets.

@gnugat
Last active May 12, 2017 09:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnugat/492a192f9f57c00098b1 to your computer and use it in GitHub Desktop.
Save gnugat/492a192f9f57c00098b1 to your computer and use it in GitHub Desktop.
A Middleware preventing Doctrine DBAL to change the database, useful for tests
<?php
namespace Gnugat\StackRollback;
use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Example:
*
* ```php
* <?php
*
* namespace AppBundle\Tests\Controller;
*
* use Gnugat\StackRollback\Rollback;
*
* class ProfileControllerTest extends \PHPUnit_Framework_TestCase
* {
* private $app;
*
* protected function setUp()
* {
* $app = new \AppKenrel('test', false);
* $app->boot();
* $connection = $app->getContainer()->get('doctrine.dbal.default_connection');
* $this->app = new Rollback($app, $connection);
* }
*
* public function testProfileCreation()
* {
* $request = new Request('/api/v1/profiles', 'POST');
* $response = $this->app->handle($request);
* $this->assertSame(201, $response->getSatusCode(), $response->getContent());
* }
* }
* ```
*/
class Rollback implements HttpKernelInterface
{
/**
* @var HttpKernelInterface
*/
private $app;
/**
* @var Connection
*/
private $connection;
/**
* @param HttpKernelInterface $app
* @param Connection $connection
*/
public function __construct(HttpKernelInterface $app, Connection $connection)
{
$this->app = $app;
$this->connection = $connection;
}
/**
* {@inheritDoc}
*/
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$this->connection->beginTransaction();
$response = $this->app->handle($request, $type, $catch);
$this->connection->rollback();
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment