VOOZH about

URL: https://deepwiki.com/hypervel/http/5.1-headerutils

⇱ HeaderUtils | hypervel/http | DeepWiki


Loading...
Menu

HeaderUtils

Purpose and Scope

HeaderUtils is a static utility class that provides low-level functions for parsing, manipulating, and generating HTTP headers. It handles header value splitting, quoting, combining parameters, Content-Disposition header generation, query string parsing, and Range request validation.

For higher-level content negotiation and Accept header processing, see Accept Header Parsing.

Sources: src/HeaderUtils.php1-372


Class Overview

HeaderUtils is designed as a non-instantiable utility class (private constructor) providing static methods for HTTP header operations. The class originates from the Symfony HTTP Foundation component and has been adapted for use in the Hypervel framework.

Constants and Static Properties

Constant/PropertyValuePurpose
DISPOSITION_ATTACHMENT'attachment'Content-Disposition type for downloadable files
DISPOSITION_INLINE'inline'Content-Disposition type for inline display
$formatsArray mappingMaps format names (html, json, xml, etc.) to MIME types

The $formats array provides bidirectional mappings between format names and their corresponding MIME types, supporting common web formats including HTML, JSON, XML, JavaScript, CSS, and more.

Sources: src/HeaderUtils.php24-49


Method Categories


Sources: src/HeaderUtils.php51-372


Header Parsing Methods

split()

Splits an HTTP header value by one or more separators, respecting quoted strings and producing a nested array structure.

Method Signature:


Parameters:

  • $header: The header value to split
  • $separators: Characters to split on, ordered by precedence (e.g., ',', ';', ',;=')

Return Value: Nested array with as many levels as there are separator characters.

Example Usage:

Input: "da, en-gb;q=0.8"
Separators: ",;"
Output: [["da"], ["en-gb", "q=0.8"]]

The method uses regular expressions to tokenize the header while preserving quoted strings and handling escape sequences. The parsing respects RFC-compliant token and quoted-string constructs.

Sources: src/HeaderUtils.php51-92

combine()

Combines an array of arrays into a single associative array, where the first element becomes the key (lowercased) and the second becomes the value (or true if only one element exists).

Method Signature:


Example:

Input: [['foo', 'abc'], ['bar']]
Output: ['foo' => 'abc', 'bar' => true]

This method is typically used after split() to create a key-value map from parsed header parameters.

Sources: src/HeaderUtils.php94-117

toString()

Joins an associative array into a header string, quoting values when necessary.

Method Signature:


Parameters:

  • $assoc: Associative array of header parameters
  • $separator: Separator character (e.g., ',' or ';')

Example:

Input: ['foo' => 'abc', 'bar' => true, 'baz' => 'a b c'], ','
Output: "foo=abc, bar, baz=\"a b c\""

Values containing special characters are automatically quoted using quote().

Sources: src/HeaderUtils.php119-143

Parsing Flow Diagram


Sources: src/HeaderUtils.php51-143


String Encoding Methods

quote()

Encodes a string as a quoted string if it contains characters not allowed in HTTP tokens. If the string matches the token pattern (alphanumeric and certain special characters), it is returned unchanged.

Method Signature:


Token Pattern: [a-z0-9!#$%&'*.^_|~-]+`

Behavior:

  • String matches token pattern → returned unchanged
  • String contains other characters → backslash-escaped and quoted

Sources: src/HeaderUtils.php145-159

unquote()

Decodes a quoted string by removing quotes and unescaping backslash sequences.

Method Signature:


This method reverses the encoding performed by quote(), using a regular expression to remove escape sequences and surrounding quotes.

Sources: src/HeaderUtils.php161-170


Content-Disposition Header Generation

makeDisposition()

Generates a properly formatted HTTP Content-Disposition header value, handling filename encoding for both ASCII and Unicode filenames according to RFC 6266.

Method Signature:


Parameters:

  • $disposition: Either DISPOSITION_ATTACHMENT or DISPOSITION_INLINE
  • $filename: Unicode filename
  • $filenameFallback: ASCII-only fallback (defaults to $filename if omitted)

Validation Rules:


Output Format:

  • If filename is ASCII: attachment; filename=file.pdf
  • If filename is Unicode: attachment; filename=file.pdf; filename*=utf-8''%E2%80%A6

The filename* parameter uses RFC 5987 encoding with UTF-8 charset and percent-encoding.

Sources: src/HeaderUtils.php172-216


Query String Parsing

parseQuery()

Parses query strings similar to PHP's parse_str(), but preserves dots in variable names and handles special characters more carefully.

Method Signature:


Parameters:

  • $query: The query string to parse
  • $ignoreBrackets: If true, treats brackets literally instead of creating nested arrays
  • $separator: The parameter separator (default: &)

Key Differences from parse_str():

Featureparse_str()HeaderUtils::parseQuery()
Dots in keysConverted to underscoresPreserved
Null bytesNot explicitly handledTruncated at null byte
Bracket handlingAlways creates arraysOptional via $ignoreBrackets

Processing Flow:


The method uses a two-pass encoding strategy: first hex-encoding key bases to preserve dots, then calling parse_str(), then hex-decoding to restore the original keys.

Sources: src/HeaderUtils.php218-274


Range Request Validation

validateRangeHeaders()

Validates and parses HTTP Range header values, returning the start and end byte positions for partial content delivery.

Method Signature:


Parameters:

  • $rangeHeader: The value of the Range header (e.g., "bytes=0-499")
  • $fileSize: Optional file size in bytes for validation

Return Value: Array containing [$start, $end] byte positions

Range Header Formats:

FormatExampleMeaning
bytes=start-endbytes=0-499Bytes 0 through 499 (500 bytes)
bytes=start-bytes=500-From byte 500 to end of file
bytes=-countbytes=-500Last 500 bytes of file

Validation Logic:


Exception Handling:

The method throws RangeNotSatisfiableHttpException with a Content-Range header in two scenarios:

  1. Suffix range requested without file size: Content-Range: bytes */*
  2. Invalid range: Content-Range: bytes */fileSize

This allows proper HTTP 416 (Range Not Satisfiable) responses.

Sources: src/HeaderUtils.php276-328


Format Mappings

The static $formats property provides a mapping between format names and their associated MIME types. This is used for content negotiation and response type detection throughout the framework.

Supported Formats

FormatMIME Types
htmltext/html, application/xhtml+xml
txttext/plain
jsapplication/javascript, application/x-javascript, text/javascript
csstext/css
jsonapplication/json, application/x-json
jsonldapplication/ld+json
xmltext/xml, application/xml, application/x-xml
rdfapplication/rdf+xml
atomapplication/atom+xml
rssapplication/rss+xml
formapplication/x-www-form-urlencoded, multipart/form-data

This mapping is particularly useful when combined with Accept header parsing (see Accept Header Parsing) to determine the best response format for a client.

Sources: src/HeaderUtils.php30-42


Usage in the Framework

HeaderUtils is used throughout the Hypervel HTTP library for:

  1. Request Processing: Parsing complex header values in the Request class
  2. Content Negotiation: Working with AcceptHeader to determine preferred formats
  3. Response Generation: Creating properly formatted headers in the Response class
  4. CORS Handling: Parsing and validating CORS-related headers in HandleCors middleware
  5. File Downloads: Generating Content-Disposition headers for file responses
  6. Range Requests: Supporting partial content delivery for streaming media

Sources: src/HeaderUtils.php1-372


Implementation Notes

Private Helper Methods

The class includes a private groupParts() method that recursively groups parsed header parts based on the separator hierarchy. This method is called by split() and handles the complex logic of building nested arrays from flat token matches.

Sources: src/HeaderUtils.php330-371

Origin and Licensing

HeaderUtils is adapted from the Symfony HTTP Foundation component and retains the original copyright notice from Fabien Potencier. It has been integrated into Hypervel to provide consistent header handling across the framework.

Sources: src/HeaderUtils.php1-10

Type Safety

All methods use strict type declarations (declare(strict_types=1)), ensuring type safety at runtime. The class throws InvalidArgumentException for invalid inputs and RangeNotSatisfiableHttpException for invalid range requests.

Sources: src/HeaderUtils.php12-372