VOOZH about

URL: https://deepwiki.com/hypervel/http/2.3-headers-and-content-negotiation

⇱ Headers & Content Negotiation | hypervel/http | DeepWiki


Loading...
Menu

Headers & Content Negotiation

Purpose & Scope

This document covers HTTP header access and content negotiation capabilities in the Request system. It explains how to retrieve request headers, parse Accept headers, perform content negotiation to determine appropriate response formats, and utilize header manipulation utilities.

For information about request input data and parameters, see Input & Parameters. For response header configuration, see Response Types.

Header Access

The Request class provides direct access to HTTP headers through the inherited header() method and the headers() convenience method.


Sources: src/Request.php755-759 src/Request.php763-777

Basic Header Retrieval

MethodReturn TypeDescription
header($key, $default)string|nullRetrieves a single header value (inherited from Hyperf)
headers()arrayReturns all request headers
bearerToken()string|nullExtracts Bearer token from Authorization header

The bearerToken() method specifically looks for "Bearer " prefix in the Authorization header and handles comma-separated token lists by returning only the first token.

Sources: src/Request.php755-777 src/Contracts/RequestContract.php326-333

Content Negotiation

Content negotiation determines the most appropriate response format based on the client's Accept header. The Request class provides multiple methods for evaluating client content type preferences.


Sources: src/Request.php444-547 src/AcceptHeader.php46-60

Content Type Detection Methods

The Request class provides several methods for determining what content types the client accepts:

MethodReturn TypeDescriptionUse Case
accepts($types)boolChecks if any provided type is acceptableConditional response formatting
acceptsJson()boolChecks if application/json is acceptableAPI endpoint detection
acceptsHtml()boolChecks if text/html is acceptableWeb page endpoint detection
acceptsAnyContentType()boolChecks if client accepts */* or has no Accept headerPermissive responses
wantsJson()boolChecks if first Accept item is JSONStrict JSON preference
expectsJson()boolHeuristic combining AJAX detection and accept typesSmart JSON detection

Sources: src/Request.php444-547 src/Contracts/RequestContract.php209-241

Accept Matching Algorithm

The accepts() method implements a flexible matching algorithm:


Sources: src/Request.php465-488

The matching supports:

  • Exact type matching (e.g., application/json)
  • Wildcard matching (e.g., */* or text/*)
  • Structured suffix matching (e.g., application/vnd.api+json matches application/json)

Preference Selection

The prefers() method returns the most preferred content type from a provided list:


The method iterates through accepted types in quality order and returns the first match from the provided list. If a wildcard */* or * is encountered, it returns the first item in the provided list.

Sources: src/Request.php493-519 src/Contracts/RequestContract.php224-226

JSON Detection Logic

Two methods provide different approaches to JSON detection:

wantsJson() - Strict detection checking if the first Accept header item contains JSON:

Accept: application/json, text/html
→ Returns true (first item is JSON)

Accept: text/html, application/json
→ Returns false (first item is not JSON)

expectsJson() - Heuristic combining multiple factors:


This returns true if:

  • Request is AJAX (X-Requested-With: XMLHttpRequest)
  • AND not PJAX (X-PJAX: true)
  • AND accepts any content type (/ or no Accept header)
  • OR wants JSON (first Accept item is JSON)

Sources: src/Request.php444-460

Accept Header Parsing

The AcceptHeader and AcceptHeaderItem classes provide structured parsing of Accept-style headers with quality values and parameters.


Sources: src/AcceptHeader.php src/AcceptHeaderItem.php

AcceptHeader Class

The AcceptHeader class parses and manages Accept-style headers with multiple items and quality values.

Parsing Example:

Accept: text/html,application/json;q=0.9,text/plain;q=0.8,*/*;q=0.1

Parsed structure:
1. text/html (q=1.0, index=0)
2. application/json (q=0.9, index=1)
3. text/plain (q=0.8, index=2)
4. */* (q=0.1, index=3)

The class automatically sorts items by:

  1. Quality value (descending)
  2. Original index (ascending, for equal quality)

Key Methods:

MethodDescription
AcceptHeader::fromString($header)Static factory parsing header string
has($value)Check if specific value exists
get($value)Retrieve item by value (with wildcard fallback)
all()Get all items sorted by quality
first()Get highest quality item
filter($pattern)Filter items by regex pattern

Sources: src/AcceptHeader.php24-160

AcceptHeaderItem Class

Represents a single item within an Accept header with its quality, attributes, and parsing order.

Structure:

application/json;q=0.9;level=1

Components:
- value: "application/json"
- quality: 0.9
- attributes: ["level" => "1"]
- index: (order in original header)

The q parameter is automatically extracted to the quality property, while other parameters remain in attributes.

Sources: src/AcceptHeaderItem.php21-164

Quality-Based Sorting

The sorting algorithm in AcceptHeader ensures correct precedence:


This ensures that:

  1. Higher quality values appear first
  2. When qualities are equal, original order is preserved

Sources: src/AcceptHeader.php132-148

MIME Type Mapping

The system provides MIME type mapping between format names and media types through HeaderUtils::$formats and related methods.

Format-to-MIME Mapping

The HeaderUtils::$formats array defines standard format mappings:

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

Sources: src/HeaderUtils.php30-42

MIME Type Retrieval Methods

The Request class provides methods to look up MIME types:


These methods directly access HeaderUtils::$formats to retrieve the mapping.

Sources: src/Request.php794-807 src/Contracts/RequestContract.php342-352

Content Type Matching with MIME Types

The prefers() method uses MIME type lookup to match format names:


The method converts format names to MIME types using getMimeType() before performing the match.

Sources: src/Request.php493-519

HeaderUtils Utility Class

The HeaderUtils class provides static utility methods for header manipulation, parsing, and validation.


Sources: src/HeaderUtils.php24-372

Header Parsing

The split() method parses headers with multiple levels of separators:


The method respects quoted strings and handles multiple precedence levels of separators.

Sources: src/HeaderUtils.php65-92

Header Assembly

The combine() and toString() methods work together to build headers:


Sources: src/HeaderUtils.php107-143

Content-Disposition Generation

The makeDisposition() method generates RFC 6266 compliant Content-Disposition headers:


This is used by the Response system when serving file downloads with non-ASCII filenames.

Sources: src/HeaderUtils.php185-216

Range Header Validation

The validateRangeHeaders() method parses and validates HTTP Range requests:


This is used internally by the streaming response system to support partial content requests.

Sources: src/HeaderUtils.php286-328

Integration with Request Pipeline

Header processing and content negotiation integrate with the broader request handling system:


Sources: src/Request.php444-519 src/AcceptHeader.php46-60

The content negotiation system enables controllers to make intelligent decisions about response format based on client preferences, supporting both API and web application use cases within the same application.