forked from laysense/laysite
Expand admin system information and license notices
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Content;
|
||||
|
||||
use Composer\InstalledVersions;
|
||||
|
||||
final class SystemInfo
|
||||
{
|
||||
public static function version(string $package): string
|
||||
{
|
||||
return InstalledVersions::isInstalled($package)
|
||||
? InstalledVersions::getPrettyVersion($package) ?? '未知'
|
||||
: '未知';
|
||||
}
|
||||
|
||||
public static function platform(): string
|
||||
{
|
||||
if (PHP_OS_FAMILY === 'Linux') {
|
||||
foreach (['/etc/os-release', '/usr/lib/os-release'] as $path) {
|
||||
if (!is_readable($path)) {
|
||||
continue;
|
||||
}
|
||||
$release = @parse_ini_file($path, false, INI_SCANNER_RAW);
|
||||
$name = $release['PRETTY_NAME'] ?? $release['NAME'] ?? '';
|
||||
$version = $release['VERSION_ID'] ?? '';
|
||||
if ($name !== '') {
|
||||
return $version !== '' && !str_contains($name, $version) ? $name . ' ' . $version : $name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PHP_OS_FAMILY;
|
||||
}
|
||||
|
||||
public static function sample(): array
|
||||
{
|
||||
return [
|
||||
'cpu' => PHP_OS_FAMILY === 'Linux' ? self::cpu() : null,
|
||||
'memory' => PHP_OS_FAMILY === 'Linux' ? self::memory() : null,
|
||||
];
|
||||
}
|
||||
|
||||
private static function cpu(): ?array
|
||||
{
|
||||
$file = @fopen('/proc/stat', 'r');
|
||||
if ($file === false) {
|
||||
return null;
|
||||
}
|
||||
$line = fgets($file);
|
||||
fclose($file);
|
||||
if ($line === false || !preg_match('/^cpu\h+(?:\d+\h+){7}\d+/', $line)) {
|
||||
return null;
|
||||
}
|
||||
$fields = array_map('intval', explode(' ', preg_replace('/\s+/', ' ', trim($line))));
|
||||
// Exclude the guest fields. Linux already counts them in user and nice time.
|
||||
return ['total' => array_sum(array_slice($fields, 1, 8)), 'idle' => $fields[4] + $fields[5]];
|
||||
}
|
||||
|
||||
private static function memory(): ?string
|
||||
{
|
||||
$info = @file_get_contents('/proc/meminfo');
|
||||
if ($info === false || !preg_match('/^MemTotal:\s+(\d+) kB$/m', $info, $total)
|
||||
|| !preg_match('/^MemAvailable:\s+(\d+) kB$/m', $info, $available) || (int) $total[1] === 0) {
|
||||
return null;
|
||||
}
|
||||
$capacity = (int) $total[1] * 1024;
|
||||
$used = max(0, $capacity - (int) $available[1] * 1024);
|
||||
|
||||
return sprintf('%s / %s(%.1f%%)', self::bytes($used), self::bytes($capacity), 100 * $used / $capacity);
|
||||
}
|
||||
|
||||
public static function bytes(int|float $bytes): string
|
||||
{
|
||||
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
||||
$unit = 0;
|
||||
while ($bytes >= 1024 && $unit < count($units) - 1) {
|
||||
$bytes /= 1024;
|
||||
$unit++;
|
||||
}
|
||||
|
||||
return ($unit === 0 ? (string) $bytes : number_format($bytes, 1)) . ' ' . $units[$unit];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user