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

PingConnectionMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
dl 0
loc 34
rs 10
c 1
b 0
f 1
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A execute() 0 8 2
A ping() 0 10 2
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