Last active
May 12, 2017 09:24
-
-
Save gnugat/492a192f9f57c00098b1 to your computer and use it in GitHub Desktop.
A Middleware preventing Doctrine DBAL to change the database, useful for tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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