This repository has been archived by the owner on Nov 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPingController.php
95 lines (78 loc) · 2.71 KB
/
PingController.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
92
93
94
95
<?php
declare(strict_types=1);
namespace Libero\PingController;
use ErrorException;
use Exception;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\Log\NullLogger;
use RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
use function call_user_func;
use function in_array;
use function restore_error_handler;
use function set_error_handler;
use const E_DEPRECATED;
use const E_USER_DEPRECATED;
final class PingController
{
private $test;
private $logger;
public function __construct(?callable $test = null, ?LoggerInterface $logger = null)
{
$this->test = $test;
$this->logger = $logger;
}
public function __invoke(Request $request) : Response
{
if ($this->test) {
$this->ensureLogger();
set_error_handler(
function (int $severity, string $message, string $file, int $line) : bool {
if (in_array($severity, [E_DEPRECATED, E_USER_DEPRECATED], true)) {
$this->logger->log(LogLevel::NOTICE, $message);
return true;
}
throw new ErrorException($message, 0, $severity, $file, $line);
}
);
try {
call_user_func($this->test);
} catch (RuntimeException $e) {
$this->logger->critical('Ping failed', ['exception' => $e]);
return $this->createResponse($request, Response::HTTP_SERVICE_UNAVAILABLE);
} catch (Throwable $e) {
$this->logger->log(
$e instanceof Exception ? LogLevel::ERROR : LogLevel::CRITICAL,
'Ping failed',
['exception' => $e]
);
return $this->createResponse($request, Response::HTTP_INTERNAL_SERVER_ERROR);
} finally {
restore_error_handler();
}
}
return $this->createResponse($request, Response::HTTP_OK, 'pong');
}
private function createResponse(Request $request, int $statusCode, ?string $content = null) : Response
{
$response = new Response(
$content ?? Response::$statusTexts[$statusCode],
$statusCode,
[
'Cache-Control' => 'must-revalidate, no-store',
'Content-Type' => 'text/plain; charset=utf-8',
]
);
if ('HTTP/1.0' === $request->getProtocolVersion()) {
$response->headers->set('Expires', '0');
}
return $response;
}
private function ensureLogger() : void
{
$this->logger = $this->logger ?? new NullLogger();
}
}