You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.3 KiB
53 lines
1.3 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* @author Robert Strutts
|
|
* @copyright (c) 2026, Robert Strutts
|
|
* @license MIT
|
|
*/
|
|
|
|
namespace IOcornerstone\Framework;
|
|
|
|
use IOcornerstone\Framework\Enum\CompressionMethod as Method;
|
|
|
|
final class GzCompression
|
|
{
|
|
|
|
public function __construct(
|
|
public Method $method = Method::DEFLATE,
|
|
public int $compressionLevel = 4,
|
|
public bool $useCompression = true
|
|
)
|
|
{}
|
|
|
|
public function compress(string $data): string|false
|
|
{
|
|
if ($this->useCompression === false) {
|
|
return false;
|
|
}
|
|
|
|
$level = ($this->compressionLevel < 10 && $this->compressionLevel > 0) ? $this->compressionLevel : 4;
|
|
|
|
$c = match ($this->method) {
|
|
Method::DEFLATE => gzdeflate($data, $level),
|
|
Method::GZIP => gzencode($data, $level),
|
|
Method::ZLIB => gzcompress($data, $level),
|
|
};
|
|
return base64_encode($c);
|
|
}
|
|
|
|
public function decompress(string $compressed_data): string|false
|
|
{
|
|
if ($this->useCompression === false) {
|
|
return false;
|
|
}
|
|
$d = base64_decode($compressed_data);
|
|
return match ($this->method) {
|
|
Method::DEFLATE => gzinflate($d),
|
|
Method::GZIP => gzdecode($d),
|
|
Method::ZLIB => gzuncompress($d),
|
|
};
|
|
}
|
|
}
|
|
|