<?php

namespace NoahVet\Reef\Domain\Http\Header;

use NoahVet\Reef\Domain\Exception\InvalidContentRangeException;

class ContentRangeHttpHeader
{
    /**
     * Parse Content-Rage header. Supported formats :
     *  - <unit> <range>/<size>
     *
     * @return array{unit: string, rangeStart: int, rangeEnd: int, size: int}
     *
     * @throws InvalidContentRangeException
     */
    public static function parse(string $headerLine): array
    {
        if (!\preg_match('/^(\w+) (\d+)-(\d+)\/(\d+)$/', $headerLine, $matches)) {
            throw new InvalidContentRangeException('Invalid Content-Range header');
        }

        return [
            'unit' => $matches[1],
            'rangeStart' => (int) $matches[2],
            'rangeEnd' => (int) $matches[3],
            'size' => (int) $matches[4],
        ];
    }
}
