forked from swarrot/swarrot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionProcessor.php
91 lines (83 loc) · 3 KB
/
ConnectionProcessor.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace Swarrot\Processor\Doctrine;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Connections\MasterSlaveConnection;
use Doctrine\DBAL\DBALException as DBAL2Exception;
use Doctrine\DBAL\Exception as DBAL3Exception;
use Doctrine\Persistence\ConnectionRegistry;
use Swarrot\Broker\Message;
use Swarrot\Processor\ConfigurableInterface;
use Swarrot\Processor\ProcessorInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Adrien Brault <[email protected]>
*/
class ConnectionProcessor implements ConfigurableInterface
{
private $processor;
/**
* @var Connection[]
*/
private $connections;
/**
* @param ConnectionRegistry|Connection[]|Connection $connections
*/
public function __construct(ProcessorInterface $processor, $connections)
{
if ($connections instanceof ConnectionRegistry) {
$connections = $connections->getConnections();
} elseif ($connections instanceof Connection) {
$connections = [$connections];
} elseif (\is_array($connections)) {
foreach ($connections as $connection) {
if (!$connection instanceof Connection) {
throw new \InvalidArgumentException(sprintf('$connections must be an array of Connection, but one of the elements was %s', \is_object($connection) ? \get_class($connection) : \gettype($connection)));
}
}
} else {
throw new \InvalidArgumentException('$connections must be an array of Connection, a ConnectionRegistry or a single Connection.');
}
$this->processor = $processor;
$this->connections = $connections;
}
/**
* {@inheritdoc}
*/
public function process(Message $message, array $options): bool
{
if ($options['doctrine_ping']) {
foreach ($this->connections as $connection) {
if ($connection->isConnected()) {
try {
$connection->query($connection->getDatabasePlatform()->getDummySelectSQL());
} catch (DBAL2Exception | DBAL3Exception $e) {
$connection->close(); // close timed out connections so that using them connects again
}
}
}
}
try {
return $this->processor->process($message, $options);
} finally {
if ($options['doctrine_close_master']) {
foreach ($this->connections as $connection) {
if ($connection instanceof MasterSlaveConnection
&& $connection->isConnectedToMaster()
) {
$connection->close();
}
}
}
}
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'doctrine_ping' => true,
'doctrine_close_master' => true,
]);
}
}