From be8aba8e3bbf830a961c4c58230193716641552d Mon Sep 17 00:00:00 2001 From: Brian Moon Date: Thu, 16 May 2024 13:21:35 -0500 Subject: [PATCH] Add option to close the connection --- src/PDO.php | 20 ++++++++++++++++++++ tests/PDOTest.php | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/PDO.php b/src/PDO.php index 0334173..26e9d50 100644 --- a/src/PDO.php +++ b/src/PDO.php @@ -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 * diff --git a/tests/PDOTest.php b/tests/PDOTest.php index 0a25de9..406457a 100644 --- a/tests/PDOTest.php +++ b/tests/PDOTest.php @@ -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); @@ -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); } } }