-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* feat: add system time checker (#314) * fix: code-style
- Loading branch information
1 parent
c9faac5
commit cca746f
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
57 changes: 57 additions & 0 deletions
57
src/Components/Health/Checker/HealthChecker/SystemTimeChecker.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
<?php | ||
|
||
declare (strict_types=1); | ||
|
||
namespace Frosh\Tools\Components\Health\Checker\HealthChecker; | ||
|
||
use Frosh\Tools\Components\Health\Checker\CheckerInterface; | ||
use Frosh\Tools\Components\Health\HealthCollection; | ||
use Frosh\Tools\Components\Health\SettingsResult; | ||
use GuzzleHttp\Client; | ||
use GuzzleHttp\Exception\GuzzleException; | ||
|
||
class SystemTimeChecker implements HealthCheckerInterface, CheckerInterface | ||
{ | ||
public function collect(HealthCollection $collection): void | ||
{ | ||
$this->checkSystemTime($collection); | ||
} | ||
|
||
private function checkSystemTime(HealthCollection $collection): void | ||
{ | ||
$url = 'https://cloudflare.com/cdn-cgi/trace'; | ||
$snippet = 'System time'; | ||
$recommended = 'max 5 seconds'; | ||
|
||
try { | ||
$response = (new Client())->request('GET', $url); | ||
|
||
$data = []; | ||
$lines = explode("\n", trim((string) $response->getBody())); | ||
foreach ($lines as $line) { | ||
if (str_contains($line, '=')) { | ||
[$key, $value] = explode("=", $line, 2); | ||
$data[$key] = $value; | ||
} | ||
} | ||
|
||
$cloudflareTimestamp = isset($data['ts']) ? (int) $data['ts'] : null; | ||
if (!$cloudflareTimestamp) { | ||
$status = SettingsResult::info('system-time', $snippet, 'Could not parse remote time', $recommended, $url); | ||
$collection->add($status); | ||
return; | ||
} | ||
|
||
$diff = abs(time() - $cloudflareTimestamp); | ||
if ($diff > 5) { | ||
$status = SettingsResult::warning('system-time', $snippet, $diff . ' seconds', $recommended); | ||
} else { | ||
$status = SettingsResult::ok('system-time', $snippet, $diff . ' second(s)', $recommended); | ||
} | ||
} catch (GuzzleException) { | ||
$status = SettingsResult::info('system-time', $snippet, 'Could not fetch remote time', $recommended, $url); | ||
} | ||
|
||
$collection->add($status); | ||
} | ||
} |