Files
portal-api/app/Services/CompressionService.php

84 lines
2.7 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Http\Request;
class CompressionService
{
/**
* Check compression capabilities of the client
*/
public static function getClientCapabilities(Request $request): array
{
$acceptEncoding = $request->header('Accept-Encoding', '');
return [
'supports_gzip' => str_contains($acceptEncoding, 'gzip'),
'supports_deflate' => str_contains($acceptEncoding, 'deflate'),
'supports_brotli' => str_contains($acceptEncoding, 'br'),
'raw_header' => $acceptEncoding,
];
}
/**
* Get compression info for debugging
*/
public static function getCompressionInfo(string $content): array
{
$originalSize = strlen($content);
$info = ['original_size' => $originalSize];
if (function_exists('gzencode')) {
$gzipped = gzencode($content, 6);
if ($gzipped !== false) {
$gzippedSize = strlen($gzipped);
$info['gzip'] = [
'compressed_size' => $gzippedSize,
'ratio' => round(($gzippedSize / $originalSize) * 100, 2) . '%',
'savings' => round((1 - $gzippedSize / $originalSize) * 100, 2) . '%'
];
}
}
if (function_exists('gzdeflate')) {
$deflated = gzdeflate($content, 6);
if ($deflated !== false) {
$deflatedSize = strlen($deflated);
$info['deflate'] = [
'compressed_size' => $deflatedSize,
'ratio' => round(($deflatedSize / $originalSize) * 100, 2) . '%',
'savings' => round((1 - $deflatedSize / $originalSize) * 100, 2) . '%'
];
}
}
if (function_exists('brotli_compress')) {
$brotlied = brotli_compress($content, 6);
if ($brotlied !== false) {
$brotliedSize = strlen($brotlied);
$info['brotli'] = [
'compressed_size' => $brotliedSize,
'ratio' => round(($brotliedSize / $originalSize) * 100, 2) . '%',
'savings' => round((1 - $brotliedSize / $originalSize) * 100, 2) . '%'
];
}
}
return $info;
}
/**
* Format bytes to human readable format
*/
public static function formatBytes(int $bytes, int $precision = 2): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
}
return round($bytes, $precision) . ' ' . $units[$i];
}
}