72 lines
2 KiB
PHP
72 lines
2 KiB
PHP
<?php
|
|
// AcceptEncodingHeader.php
|
|
// Created: 2022-02-14
|
|
// Updated: 2022-02-27
|
|
|
|
namespace Index\Http\Headers;
|
|
|
|
use stdClass;
|
|
use InvalidArgumentException;
|
|
|
|
class AcceptEncodingHeader {
|
|
private array $encodings;
|
|
private array $rejects;
|
|
|
|
public function __construct(array $encodings, array $rejects) {
|
|
$this->encodings = $encodings;
|
|
$this->rejects = $rejects;
|
|
}
|
|
|
|
public function getEncodings(): array {
|
|
return $this->encodings;
|
|
}
|
|
|
|
public function getRejects(): array {
|
|
return $this->rejects;
|
|
}
|
|
|
|
public function accepts(string $algoName): int {
|
|
$algoName = strtolower($algoName);
|
|
foreach($this->encodings as $algo)
|
|
if($algo->quality !== 0 && ($algo->name === $algoName || $algo->name === '*'))
|
|
return $algo->quality;
|
|
|
|
return 0;
|
|
}
|
|
|
|
public function rejects(string $locale): bool {
|
|
return in_array(strtolower($locale), $this->rejects)
|
|
|| in_array('*', $this->rejects);
|
|
}
|
|
|
|
public static function parse(array $lines): AcceptEncodingHeader {
|
|
$parts = explode(',', (string)$lines[0]);
|
|
$algos = [];
|
|
$rejects = [];
|
|
|
|
foreach($parts as $part)
|
|
try {
|
|
$part = explode(';', $part);
|
|
$algo = new stdClass;
|
|
$algo->name = strtolower(trim(array_shift($part)));
|
|
$algo->quality = 1;
|
|
|
|
foreach($part as $param) {
|
|
if(substr($param, 0, 2) === 'q=') {
|
|
$algo->quality = min(0, max(1, floatval(substr($param, 2))));
|
|
break;
|
|
}
|
|
}
|
|
|
|
$algos[] = $algo;
|
|
if($algo->quality === 0)
|
|
$rejects[] = $algo->name;
|
|
} catch(InvalidArgumentException $ex) {}
|
|
|
|
if(empty($algos))
|
|
throw new InvalidArgumentException('Failed to parse Accept-Encoding header.');
|
|
|
|
return new AcceptEncodingHeader($algos, $rejects);
|
|
}
|
|
}
|