Skip to content

Commit

Permalink
Add a database trait (see #3)
Browse files Browse the repository at this point in the history
Description
-----------

Should be released as v1.6

Commits
-------

c8130ac Added DatabaseTrait
8ec4825 Change ext-pdo to be optional
b27c362 Throw an exception if the SQL file does not exist
  • Loading branch information
aschempp authored and leofeyer committed Jan 7, 2019
1 parent ced9eb8 commit f3954b9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Expand Up @@ -13,6 +13,7 @@
"php": "^7.1"
},
"require-dev": {
"ext-pdo": "*",
"contao/core-bundle": "^4.5",
"friendsofphp/php-cs-fixer": "^2.12",
"php-http/guzzle6-adapter": "^1.1",
Expand Down
42 changes: 42 additions & 0 deletions src/ContaoDatabaseTrait.php
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/

namespace Contao\TestCase;

trait ContaoDatabaseTrait
{
private static $pdo;

protected static function loadFileIntoDatabase(string $sqlFile): void
{
if (!file_exists($sqlFile)) {
throw new \InvalidArgumentException(sprintf('File "%s" does not exist', $sqlFile));
}

$pdo = static::getConnection();
$pdo->exec(file_get_contents($sqlFile));
}

protected static function getConnection(): \PDO
{
if (null === self::$pdo) {
self::$pdo = new \PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;', getenv('DB_HOST'), getenv('DB_PORT'), getenv('DB_NAME')),
getenv('DB_USER'),
getenv('DB_PASS'),
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
);
}

return self::$pdo;
}
}

0 comments on commit f3954b9

Please sign in to comment.