VOOZH about

URL: https://deepwiki.com/hypervel/http/5.2-accept-header-parsing

⇱ Accept Header Parsing | hypervel/http | DeepWiki


Loading...
Menu

Accept Header Parsing

Purpose and Scope

This document describes the AcceptHeader and AcceptHeaderItem classes, which provide parsing and management of HTTP Accept-* headers (such as Accept, Accept-Language, Accept-Encoding, etc.). These classes handle quality value negotiation, wildcard matching, and proper sorting based on client preferences.

For general header manipulation utilities, see HeaderUtils. For broader content negotiation features in the Request object, see Headers & Content Negotiation.


Accept Header Structure

HTTP Accept-* headers allow clients to specify preferred content types, languages, or encodings with quality values indicating preference levels. The format follows RFC 2616:

Accept: text/html, application/json;q=0.9, */*;q=0.8
Accept-Language: en-US, en;q=0.9, fr;q=0.5
Accept-Encoding: gzip, deflate;q=0.8

Each header contains one or more items separated by commas. Items may include:

  • Value: The primary content identifier (e.g., text/html, en-US)
  • Quality (q): A float from 0.0 to 1.0 indicating preference (default: 1.0)
  • Attributes: Additional parameters specific to the item

Sources: src/AcceptHeader.php18-23 src/AcceptHeaderItem.php18-20


AcceptHeader Class

The AcceptHeader class represents a complete Accept-* header and manages a collection of AcceptHeaderItem objects sorted by quality and position.

Class Structure


Sources: src/AcceptHeader.php24-149

Parsing from String

The fromString() static method parses Accept header strings into structured objects:


The parsing process at src/AcceptHeader.php46-60:

  1. Uses HeaderUtils::split() to tokenize the header value by commas, semicolons, and equals signs
  2. Processes each token group into an AcceptHeaderItem
  3. Assigns a sequential index to maintain original order for tie-breaking
  4. Returns an AcceptHeader instance containing all items

Sources: src/AcceptHeader.php46-60

Item Retrieval with Fallback

The get() method implements intelligent fallback logic for content type matching:

PriorityPatternExample
1Exact matchtext/html matches text/html
2Type wildcardtext/* matches any text type
3Global wildcard*/* matches any type
4Single wildcard* matches anything

This implementation at src/AcceptHeader.php81-84 extracts the type from values like application/json and checks for application/* wildcards before falling back to */* or *.

Sources: src/AcceptHeader.php81-84

Quality-Based Sorting

Items are sorted by descending quality value, with the original index used as a tie-breaker:


The sorting implementation at src/AcceptHeader.php132-148:

  • Uses uasort() to maintain key associations
  • Sorts by quality in descending order (higher quality first)
  • When qualities are equal, uses index to maintain original order
  • Employs a sorted flag to avoid redundant sorting operations

Sources: src/AcceptHeader.php132-148

Type Matching

The static matchesType() method determines if a content type matches an accept pattern, supporting vendor-specific subtypes:

The method at src/AcceptHeader.php150-159 handles two cases:

  1. Exact match: application/json matches application/json
  2. Vendor subtype: application/vnd.api+json matches application/json by extracting the suffix after +

This allows patterns like application/*+json to match specialized JSON formats.

Sources: src/AcceptHeader.php150-159

Additional Methods

MethodPurposeReturn Type
has(string $value)Check if value existsbool
add(AcceptHeaderItem $item)Add item to collectionself
all()Get all items sorted by qualityAcceptHeaderItem[]
first()Get highest quality itemAcceptHeaderItem|null
filter(string $pattern)Filter items by regexAcceptHeader
__toString()Serialize to header stringstring

Sources: src/AcceptHeader.php65-127


AcceptHeaderItem Class

The AcceptHeaderItem class represents a single item within an Accept header, containing the value, quality, and additional attributes.

Item Structure


Sources: src/AcceptHeaderItem.php21-164

Property Management

The class at src/AcceptHeaderItem.php31-37 accepts a value and attributes array in its constructor:

  • Value: The primary identifier (e.g., text/html, en-US, gzip)
  • Attributes: Key-value pairs for additional parameters

The special handling at src/AcceptHeaderItem.php156-162 treats the q attribute differently:

  • When setting an attribute named q, it updates the quality property instead
  • Other attributes are stored in the attributes array
  • Quality defaults to 1.0 if not specified

Sources: src/AcceptHeaderItem.php31-37 src/AcceptHeaderItem.php156-162

String Serialization

The __toString() method at src/AcceptHeaderItem.php55-63 reconstructs the header item string:

text/html;q=0.9;level=1

Output format:

  1. Value (required): text/html
  2. Quality (if < 1.0): ;q=0.9
  3. Additional attributes: ;level=1

Uses HeaderUtils::toString() for proper attribute formatting.

Sources: src/AcceptHeaderItem.php55-63

Parsing Individual Items

The static fromString() method at src/AcceptHeaderItem.php42-50:

  1. Splits the item string using HeaderUtils::split() with delimiters ;=
  2. Extracts the value from the first part
  3. Combines remaining parts into attributes using HeaderUtils::combine()
  4. Returns a new AcceptHeaderItem instance

Sources: src/AcceptHeaderItem.php42-50


Usage Patterns

Parsing Accept Headers

The typical workflow for parsing an Accept header:


Sources: src/AcceptHeader.php46-60

Integration with Request

The AcceptHeader class integrates with the Request object's content negotiation methods:

  • Request::accepts() uses AcceptHeader to parse the Accept header
  • Request::acceptsLanguages() parses Accept-Language
  • Request::acceptsEncodings() parses Accept-Encoding

These methods leverage the quality-based sorting to determine the client's preferred content format.

Sources: src/AcceptHeader.php1-161

Quality Value Negotiation

Example quality value handling:

Header ValueQualityIndexSort Order
text/html1.001st (default quality)
application/json;q=0.90.912nd (explicit quality)
text/plain;q=0.90.923rd (tie broken by index)
*/*;q=0.80.834th (lowest quality)

The sorting ensures:

  1. Higher quality values appear first
  2. When qualities are equal, original order is preserved
  3. Wildcards with low quality serve as fallbacks

Sources: src/AcceptHeader.php132-148 src/AcceptHeaderItem.php100-103


Implementation Notes

Lazy Sorting

The AcceptHeader class uses a sorted flag at src/AcceptHeader.php31 to implement lazy sorting:

  • Set to false when items are added via add()
  • Checked before operations requiring sorted data (all(), first())
  • Prevents redundant sorting when the collection hasn't changed

Sources: src/AcceptHeader.php31 src/AcceptHeader.php91-97

Wildcard Matching

The get() method's fallback chain at src/AcceptHeader.php81-84 splits values on / to check type-level wildcards:

  • Input: application/json
  • Checks: application/jsonapplication/**/**

This enables flexible content negotiation where clients can specify broad preferences.

Sources: src/AcceptHeader.php81-84

Attribute Storage

Attributes at src/AcceptHeaderItem.php29 store non-quality parameters:

  • Language-specific: level=1 for language proficiency
  • Custom vendor parameters
  • Extension attributes

The q parameter receives special treatment to maintain the separate quality property for efficient sorting.

Sources: src/AcceptHeaderItem.php29 src/AcceptHeaderItem.php154-163

HeaderUtils Integration

Both classes depend on HeaderUtils for:

  • split(): Tokenizing header strings with multiple delimiters
  • combine(): Converting token arrays into attribute arrays
  • toString(): Serializing attributes back to string format

This separation of concerns keeps header parsing logic reusable across different header types.

Sources: src/AcceptHeader.php48 src/AcceptHeader.php53 src/AcceptHeaderItem.php44 src/AcceptHeaderItem.php47 src/AcceptHeaderItem.php59