Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -44,9 +45,9 @@ class Database
/**
* PDO connection
*
* @var \PDO $connection
* @var \PDO|null $connection
*/
private \PDO $connection;
private ?\PDO $connection;

/**
* Driver
Expand Down Expand Up @@ -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
*
Expand Down
13 changes: 13 additions & 0 deletions src/Exception/ClosedConnectionException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Access\Exception;

use Access\Exception;

class ClosedConnectionException extends Exception
{
public function __construct()
{
parent::__construct('Connection is closed');
}
}
15 changes: 15 additions & 0 deletions tests/base/BaseDatabaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Access\Database;
use Access\Exception;
use Access\Exception\ClosedConnectionException;
use Access\Query;
use PDO;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -325,4 +326,18 @@ public function testWithIncludeSoftDeleted(): void
$user = $db->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();
}
}