PingConnectionMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

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

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 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