server/app/Utils/AppInfoHelper.php

82 lines
2.3 KiB
PHP

<?php
namespace App\Utils;
use Hyperf\Context\ApplicationContext;
use Swoole\Server;
use function Hyperf\Collection\value;
class AppInfoHelper
{
private static float $startTime = 0;
public static function initStartTime(): void
{
// 避免重复初始化
if (self::$startTime == 0) {
self::$startTime = microtime(true);
}
}
public static function getInfo(): array
{
return [
'hyperf_version' => self::getHyperfVersion(),
'swoole_version' => defined('SWOOLE_VERSION') ? SWOOLE_VERSION : 'N/A',
'project_path' => BASE_PATH,
'start_time' => self::getStartTime(),
'uptime' => self::getUptime(),
];
}
private static function getHyperfVersion(): string
{
$composerFile = BASE_PATH . '/composer.lock';
if (file_exists($composerFile)) {
$composer = json_decode(file_get_contents($composerFile), true);
foreach ($composer['packages'] ?? [] as $pkg) {
if ($pkg['name'] === 'hyperf/framework') {
return $pkg['version'] ?? 'unknown';
}
}
}
return 'unknown';
}
private static function getStartTime(): string
{
$start = self::getServerStartTimestamp() ?: self::$startTime;
return $start ? date('Y-m-d H:i:s', (int)$start) : 'unknown';
}
private static function getUptime(): string
{
$start = self::getServerStartTimestamp() ?: self::$startTime;
if (!$start) {
return 'unknown';
}
$seconds = (int)(microtime(true) - $start);
return self::formatDuration($seconds);
}
private static function getServerStartTimestamp(): ?float
{
try {
$container = ApplicationContext::getContainer();
if ($container->has(Server::class)) {
$server = $container->get(Server::class);
return $server->start_time ?? null;
}
} catch (\Throwable) {
}
return null;
}
private static function formatDuration(int $seconds): string
{
$d = floor($seconds / 86400);
$h = floor(($seconds % 86400) / 3600);
$m = floor(($seconds % 3600) / 60);
return sprintf('%d天%d小时%d分钟', $d, $h, $m);
}
}