| 1 |
<?php |
| 2 |
defined('ABSPATH') or die('Unauthorized Access'); |
| 3 |
|
| 4 |
class Phpinfo_WP_OPcache { |
| 5 |
|
| 6 |
private static function _pro(): bool { return Phpinfo_WP_License::is_valid(); } |
| 7 |
|
| 8 |
public static function is_available(): bool { |
| 9 |
return function_exists('opcache_get_status') && function_exists('opcache_get_configuration'); |
| 10 |
} |
| 11 |
|
| 12 |
public static function status(): ?array { |
| 13 |
if (!self::_pro()) return null; |
| 14 |
if (!self::is_available()) return null; |
| 15 |
|
| 16 |
$status = @opcache_get_status(false); |
| 17 |
$config = @opcache_get_configuration(); |
| 18 |
|
| 19 |
if (!$status || !$config) return null; |
| 20 |
|
| 21 |
$mem = $status['memory_usage'] ?? []; |
| 22 |
$used = (int) ($mem['used_memory'] ?? 0); |
| 23 |
$free = (int) ($mem['free_memory'] ?? 0); |
| 24 |
$wasted = (int) ($mem['wasted_memory'] ?? 0); |
| 25 |
$total = $used + $free + $wasted; |
| 26 |
$hit_rate = null; |
| 27 |
|
| 28 |
$stats = $status['opcache_statistics'] ?? []; |
| 29 |
if (isset($stats['hits'], $stats['misses']) && ($stats['hits'] + $stats['misses']) > 0) { |
| 30 |
$hit_rate = round($stats['hits'] / ($stats['hits'] + $stats['misses']) * 100, 2); |
| 31 |
} |
| 32 |
|
| 33 |
return [ |
| 34 |
'enabled' => (bool) ($status['opcache_enabled'] ?? false), |
| 35 |
'full' => (bool) ($status['cache_full'] ?? false), |
| 36 |
'hit_rate' => $hit_rate, |
| 37 |
'hits' => (int) ($stats['hits'] ?? 0), |
| 38 |
'misses' => (int) ($stats['misses'] ?? 0), |
| 39 |
'cached_scripts' => (int) ($stats['num_cached_scripts'] ?? 0), |
| 40 |
'max_scripts' => (int) ($config['directives']['opcache.max_accelerated_files'] ?? 0), |
| 41 |
'memory_used' => $used, |
| 42 |
'memory_free' => $free, |
| 43 |
'memory_wasted' => $wasted, |
| 44 |
'memory_total' => $total, |
| 45 |
'memory_pct' => $total > 0 ? round($used / $total * 100, 1) : 0, |
| 46 |
'wasted_pct' => (float) ($mem['current_wasted_percentage'] ?? 0), |
| 47 |
'start_time' => (int) ($stats['start_time'] ?? 0), |
| 48 |
'last_restart' => (int) ($stats['last_restart_time'] ?? 0), |
| 49 |
'directives' => $config['directives'] ?? [], |
| 50 |
]; |
| 51 |
} |
| 52 |
|
| 53 |
public static function reset(): bool { |
| 54 |
if (!self::_pro()) return false; |
| 55 |
if (!function_exists('opcache_reset')) return false; |
| 56 |
return @opcache_reset(); |
| 57 |
} |
| 58 |
|
| 59 |
public static function format_bytes(int $bytes): string { |
| 60 |
if ($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB'; |
| 61 |
if ($bytes >= 1024) return round($bytes / 1024, 1) . ' KB'; |
| 62 |
return $bytes . ' B'; |
| 63 |
} |
| 64 |
|
| 65 |
public static function hit_rate_class(float $rate): string { |
| 66 |
if ($rate >= 90) return 'grade-a'; |
| 67 |
if ($rate >= 70) return 'grade-b'; |
| 68 |
if ($rate >= 50) return 'grade-c'; |
| 69 |
return 'grade-f'; |
| 70 |
} |
| 71 |
} |
| 72 |
|