Passed
Pull Request — master (#28)
by Witold
01:38
created

PingConnectionMiddleware::ping()   A

Complexity

Conditions 2
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 5
nop 1
dl 0
loc 16
rs 9.9332
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
        set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
45
            throw new ErrorException($message, $severity, $severity, $file, $line);
46
        });
47
48
        try {
49
            $dummySelectSQL = $connection->getDatabasePlatform()->getDummySelectSQL();
50
51
            $connection->executeQuery($dummySelectSQL);
52
53
            return true;
54
        } catch (Throwable $exception) {
55
            return false;
56
        } finally {
57
            restore_error_handler();
58
        }
59
    }
60
}
61