Skip to content

Commit

Permalink
Merge pull request #3 from dealnews/next
Browse files Browse the repository at this point in the history
Add option to close the connection
  • Loading branch information
brianlmoon authored May 16, 2024
2 parents c45ee2e + be8aba8 commit 1e6c520
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/PDO.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,26 @@ public function __construct(string $dsn, ?string $username = '', ?string $passwd
}
}

/**
* Destroys the object.
*/
public function __destruct() {
$this->close();
}

/**
* Closes the connection by setting the PDO object to null
*
* @see https://www.php.net/manual/en/pdo.connections.php
*
* @return bool
*/
public function close(): bool {
$this->pdo = null;

return true;
}

/**
* Connects to the database by creating the real \PDO object
*
Expand Down
34 changes: 31 additions & 3 deletions tests/PDOTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,29 @@ public function errorCodeData() {
];
}

public function testClose() {
$config = Factory::loadConfig(Factory::getConfig('mytestdb'));

MockPDO::$mock_attempt_count = 0;
MockPDO::$mock_throw = false;
$pdo = new class($config['dsn'], $config['user'], $config['pass'], $config['options']) extends \DealNews\DB\PDO {
public function connect($reconnect = false, ?string $pdo_class = \PDO::class) {
parent::connect($reconnect, MockPDO::class);
}
};
$this->assertTrue($pdo->ping());
$this->assertEquals(1, MockPDO::$mock_attempt_count);
$this->assertTrue($pdo->ping());
$this->assertEquals(1, MockPDO::$mock_attempt_count);

$pdo->close();
$this->assertTrue($pdo->ping());
$this->assertEquals(2, MockPDO::$mock_attempt_count);
}

public function testConnect() {
MockPDO::$mock_attempt_count = 0;
MockPDO::$mock_throw = true;
$pdo = new \DealNews\DB\PDO('foo:bar');
$pdo->connect(true, MockPDO::class);
$this->assertEquals(2, MockPDO::$mock_attempt_count);
Expand All @@ -111,10 +133,16 @@ public function testDebug() {
class MockPDO extends \PDO {
public static int $mock_attempt_count = 0;

public function __construct() {
public static $mock_throw = true;

public function __construct(string $dsn, ?string $username = '', ?string $passwd = '', ?array $options = []) {
self::$mock_attempt_count++;
if (self::$mock_attempt_count <= 1) {
throw new \PDOException('Test Exception', 0);
if (self::$mock_throw) {
if (self::$mock_attempt_count <= 1) {
throw new \PDOException('Test Exception', 0);
}
} else {
parent::__construct($dsn, $username, $passwd, $options);
}
}
}

0 comments on commit 1e6c520

Please sign in to comment.