-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.php
90 lines (78 loc) · 2.06 KB
/
Server.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
<?php declare(strict_types = 1);
/**
* Server.php
*
* @license More in LICENSE.md
* @copyright https://www.fastybird.com
* @author Adam Kadlec <adam.kadlec@fastybird.com>
* @package FastyBird:WebServerPlugin!
* @subpackage Subscribers
* @since 1.0.0
*
* @date 15.04.20
*/
namespace FastyBird\Plugin\WebServer\Subscribers;
use Doctrine\DBAL;
use FastyBird\Library\Application\Exceptions as ApplicationExceptions;
use FastyBird\Library\Application\Helpers as ApplicationHelpers;
use FastyBird\Plugin\WebServer\Events;
use FastyBird\Plugin\WebServer\Exceptions;
use Symfony\Component\EventDispatcher;
/**
* Database check subscriber
*
* @package FastyBird:WebServerPlugin!
* @subpackage Subscribers
*
* @author Adam Kadlec <adam.kadlec@fastybird.com>
*/
readonly class Server implements EventDispatcher\EventSubscriberInterface
{
public function __construct(private ApplicationHelpers\Database $database)
{
}
public static function getSubscribedEvents(): array
{
return [
Events\Startup::class => 'check',
Events\Request::class => 'request',
Events\Response::class => 'response',
];
}
/**
* @throws ApplicationExceptions\InvalidState
* @throws DBAL\Exception
* @throws Exceptions\InvalidState
*/
public function check(): void
{
// Check if ping to DB is possible...
if (!$this->database->ping()) {
// ...if not, try to reconnect
$this->database->reconnect();
// ...and ping again
if (!$this->database->ping()) {
throw new Exceptions\InvalidState('Connection to database could not be established');
}
}
}
/**
* @throws ApplicationExceptions\InvalidState
* @throws DBAL\Exception
*/
public function request(): void
{
$this->database->reconnect();
// Make sure we don't work with outdated entities
$this->database->clear();
}
/**
* @throws ApplicationExceptions\InvalidState
*/
public function response(): void
{
// Clearing Doctrine's entity manager allows
// for more memory to be released by PHP
$this->database->clear();
}
}