diff --git a/src/Database.php b/src/Database.php index 5b54aea..f49b260 100644 --- a/src/Database.php +++ b/src/Database.php @@ -19,6 +19,7 @@ use Access\Driver\Sqlite; use Access\Entity; use Access\Exception; +use Access\Exception\ClosedConnectionException; use Access\Lock; use Access\Presenter; use Access\Presenter\EntityPresenter; @@ -44,9 +45,9 @@ class Database /** * PDO connection * - * @var \PDO $connection + * @var \PDO|null $connection */ - private \PDO $connection; + private ?\PDO $connection; /** * Driver @@ -128,9 +129,26 @@ public static function create( */ public function getConnection(): \PDO { + if ($this->connection === null) { + throw new ClosedConnectionException(); + } + return $this->connection; } + /** + * Close the PDO connection by setting the property to null + * + * Note that in order for the connection to be closed, all it's instances + * must be set to null + * + * @return void + */ + public function closeConnection(): void + { + $this->connection = null; + } + /** * Set a new PDO connection * diff --git a/src/Exception/ClosedConnectionException.php b/src/Exception/ClosedConnectionException.php new file mode 100644 index 0000000..c716303 --- /dev/null +++ b/src/Exception/ClosedConnectionException.php @@ -0,0 +1,13 @@ +findOne(User::class, 1); $this->assertNotNull($user); } + + public function testCloseConnection(): void + { + $db = static::createDatabaseWithDummyData(); + + $connection = $db->getConnection(); + self::assertInstanceOf(PDO::class, $connection); + + $db->closeConnection(); + + self::expectException(ClosedConnectionException::class); + self::expectExceptionMessage('Connection is closed'); + $db->getConnection(); + } }