Passed
Pull Request — master (#28)
by Witold
07:05
created

PingConnectionMiddleware::ping()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 3
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Tactician\Doctrine\DBAL;
6
7
use Doctrine\DBAL\Connection;
8
use ErrorException;
9
use League\Tactician\Middleware;
10
use Throwable;
11
12
use function restore_error_handler;
13
use function set_error_handler;
14
15
/**
16
 * Verifies if there is a connection established with the database. If not it will reconnect.
17
 */
18
final class PingConnectionMiddleware implements Middleware
19
{
20
    private Connection $connection;
21
22
    public function __construct(Connection $connection)
23
    {
24
        $this->connection = $connection;
25
    }
26
27
    /**
28
     * Reconnects to the database if the connection is expired.
29
     *
30
     * @return mixed
31
     */
32
    public function execute(object $command, callable $next)
33
    {
34
        if (! $this->ping($this->connection)) {
35
            $this->connection->close();
36
            $this->connection->connect();
37
        }
38
39
        return $next($command);
40
    }
41
42
    private function ping(Connection $connection): bool
43
    {
44
        try {
45
            $dummySelectSQL = $connection->getDatabasePlatform()->getDummySelectSQL();
46
47
            $connection->executeQuery($dummySelectSQL);
48
49
            return true;
50
        } catch (Throwable $exception) {
51
            return false;
52
        }
53
    }
54
}
55