62 lines
1.5 KiB
PHP
62 lines
1.5 KiB
PHP
|
<?php
|
||
|
// RangeHeader.php
|
||
|
// Created: 2022-02-14
|
||
|
// Updated: 2022-02-27
|
||
|
|
||
|
namespace Index\Http\Headers;
|
||
|
|
||
|
use stdClass;
|
||
|
use Index\Http\HttpHeader;
|
||
|
|
||
|
class RangeHeader {
|
||
|
private string $unit;
|
||
|
private array $ranges;
|
||
|
|
||
|
public function __construct(string $unit, array $ranges) {
|
||
|
$this->unit = $unit;
|
||
|
$this->ranges = $ranges;
|
||
|
}
|
||
|
|
||
|
public function getUnit(): string {
|
||
|
return $this->unit;
|
||
|
}
|
||
|
|
||
|
public function isBytes(): bool {
|
||
|
return $this->unit === 'bytes';
|
||
|
}
|
||
|
|
||
|
public function getRanges(): array {
|
||
|
return $this->ranges;
|
||
|
}
|
||
|
|
||
|
public static function parse(HttpHeader $header): RangeHeader {
|
||
|
$parts = explode('=', trim($header->getFirstLine()), 2);
|
||
|
$unit = trim($parts[0]);
|
||
|
|
||
|
$ranges = [];
|
||
|
$rawRanges = explode(',', $parts[1] ?? '', 2);
|
||
|
|
||
|
foreach($rawRanges as $raw) {
|
||
|
$raw = explode('-', trim($raw), 2);
|
||
|
$start = trim($raw[0]);
|
||
|
$end = trim($raw[1] ?? '');
|
||
|
|
||
|
$ranges[] = $range = new stdClass;
|
||
|
|
||
|
if($start === '' && is_numeric($end)) {
|
||
|
$range->type = 'suffix-length';
|
||
|
$range->length = intval($end);
|
||
|
} elseif(is_numeric($start) && $end === '') {
|
||
|
$range->type = 'start';
|
||
|
$range->start = intval($start);
|
||
|
} else {
|
||
|
$range->type = 'range';
|
||
|
$range->start = intval($start);
|
||
|
$range->end = intval($end);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return new RangeHeader($unit, $ranges);
|
||
|
}
|
||
|
}
|