PingConnectionMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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