-
Notifications
You must be signed in to change notification settings - Fork 439
/
Copy pathDoctrinePingConnectionExtension.php
65 lines (52 loc) · 1.79 KB
/
DoctrinePingConnectionExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace Enqueue\Bundle\Consumption\Extension;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use Enqueue\Consumption\Context\MessageReceived;
use Enqueue\Consumption\MessageReceivedExtensionInterface;
class DoctrinePingConnectionExtension implements MessageReceivedExtensionInterface
{
/**
* @var ManagerRegistry
*/
protected $registry;
public function __construct(ManagerRegistry $registry)
{
$this->registry = $registry;
}
public function onMessageReceived(MessageReceived $context): void
{
/** @var Connection $connection */
foreach ($this->registry->getConnections() as $connection) {
if (!$connection->isConnected()) {
continue;
}
if ($this->ping($connection)) {
continue;
}
$context->getLogger()->debug(
'[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.'
);
$connection->close();
$connection->connect();
$context->getLogger()->debug(
'[DoctrinePingConnectionExtension] Connection is active now.'
);
}
}
private function ping(Connection $connection): bool
{
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
throw new \ErrorException($message, $severity, $severity, $file, $line);
});
try {
$dummySelectSQL = $connection->getDatabasePlatform()->getDummySelectSQL();
$connection->executeQuery($dummySelectSQL);
return true;
} catch (\Throwable $exception) {
return false;
} finally {
restore_error_handler();
}
}
}