Files
awo-hamburg-intranet/module/tasks/lib/CronHeartbeat.php

73 lines
1.8 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
class CronHeartbeat
{
private static function heartbeatDir(): string
{
return dirname(__DIR__) . '/logs/heartbeat';
}
public static function record(string $jobName, array $summary = []): void
{
$dir = self::heartbeatDir();
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
$data = [
'job' => $jobName,
'timestamp' => date('c'),
'unix' => time(),
'summary' => $summary,
];
$file = $dir . '/' . preg_replace('/[^a-zA-Z0-9_-]/', '', $jobName) . '.json';
@file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
}
public static function read(string $jobName): ?array
{
$file = self::heartbeatDir() . '/' . preg_replace('/[^a-zA-Z0-9_-]/', '', $jobName) . '.json';
if (!is_file($file)) {
return null;
}
$raw = @file_get_contents($file);
if (!is_string($raw) || $raw === '') {
return null;
}
$data = json_decode($raw, true);
return is_array($data) ? $data : null;
}
public static function readAll(): array
{
$dir = self::heartbeatDir();
if (!is_dir($dir)) {
return [];
}
$results = [];
$files = @glob($dir . '/*.json');
if (!is_array($files)) {
return [];
}
foreach ($files as $file) {
$raw = @file_get_contents($file);
if (!is_string($raw) || $raw === '') {
continue;
}
$data = json_decode($raw, true);
if (is_array($data) && isset($data['job'])) {
$results[(string) $data['job']] = $data;
}
}
return $results;
}
}