VOOZH about

URL: https://deepwiki.com/hypervel/dispatcher/2.4-middleware-parsing

⇱ Middleware Parsing | hypervel/dispatcher | DeepWiki


Loading...
Menu

Middleware Parsing

Purpose and Scope

This document explains the middleware parsing functionality provided by the ParsedMiddleware class, which enables the dispatcher to process string-based middleware definitions. The parser converts signature strings like 'auth:api,admin' into structured components with a middleware name and parameter array. This capability allows applications to define middleware chains using concise string notation rather than requiring fully instantiated objects.

For information about how parsed middleware is executed within the pipeline, see Pipeline Implementation. For details on the adapter system that handles different middleware types, see Middleware Adaptation System.


ParsedMiddleware Class

The ParsedMiddleware class src/ParsedMiddleware.php7-43 serves as a value object that encapsulates the parsing logic for string-based middleware signatures. It accepts a signature string in its constructor and immediately parses it into constituent parts, storing the results as immutable properties accessible through getter methods.

Class Structure


Sources: src/ParsedMiddleware.php1-43 src/Pipeline.php31-43

Public Interface

The class provides three public getter methods:

MethodReturn TypeDescription
getName()stringReturns the parsed middleware name (left side of colon)
getParameters()arrayReturns the parsed parameter array (right side of colon, split by commas)
getSignature()stringReturns the original unparsed signature string

Sources: src/ParsedMiddleware.php18-31


String Signature Format

The parser recognizes a specific format for middleware signature strings:

middleware_name:parameter1,parameter2,parameter3

Format Specification

ComponentRequiredDescriptionExample
Middleware NameYesThe class name or identifier to resolve from containerauth, throttle, App\Middleware\CustomMiddleware
Colon SeparatorNoSeparates name from parameters:
ParametersNoComma-separated list of parameter valuesapi,admin or 60,1

Parsing Examples


Sources: src/ParsedMiddleware.php33-42


Integration with Pipeline

The Pipeline class integrates ParsedMiddleware to process both pre-parsed middleware instances and raw signature strings. This integration occurs in the carry() method during middleware chain execution.

Pipeline Processing Flow


Sources: src/Pipeline.php21-60 src/ParsedMiddleware.php7-43

Code Implementation

The pipeline's carry() method src/Pipeline.php21-60 handles ParsedMiddleware instances with this logic:

if ($pipe instanceof ParsedMiddleware || is_string($pipe)) {
 if ($pipe instanceof ParsedMiddleware) {
 $name = $pipe->getName();
 $parameters = $pipe->getParameters();
 } else {
 [$name, $parameters] = $this->parsePipeString($pipe);
 }
 
 $pipe = $this->getPipeInstance($name);
 $parameters = array_merge([$passable, $stack], $parameters);
}

This code path src/Pipeline.php31-43 demonstrates that:

  1. ParsedMiddleware instances are recognized as a distinct type
  2. Name and parameters are extracted via getter methods
  3. The name is used to resolve the actual middleware instance from the container
  4. Parameters are merged with the request ($passable) and next handler ($stack)

Sources: src/Pipeline.php31-43


Parsing Algorithm

The parsing algorithm src/ParsedMiddleware.php33-42 implements a two-stage process to extract middleware components from the signature string.

Algorithm Flow


Sources: src/ParsedMiddleware.php33-42

Implementation Details

The parseMiddleware() method src/ParsedMiddleware.php33-42 executes the following steps:

  1. Name/Parameters Split: Uses explode(':', $middleware, 2) with limit of 2 to split on the first colon only, allowing middleware names themselves to contain colons
  2. Array Padding: Applies array_pad(..., 2, []) to ensure the result always has exactly 2 elements, defaulting parameters to empty array if no colon exists
  3. Parameter Parsing: If parameters exist as a string, splits on commas using explode(',', $parameters) to create parameter array
  4. Return Value: Returns array tuple [$name, $parameters] where parameters is always an array

Edge Cases

Input StringParsed NameParsed ParametersNotes
'middleware''middleware'[]No colon, parameters default to empty array
'middleware:''middleware'['']Empty string after colon becomes single-element array
'middleware:param''middleware'['param']Single parameter
'middleware:a,b,c''middleware'['a', 'b', 'c']Multiple parameters
'ns:middleware:param'`'ns'['middleware:param']Only first colon is splitting point

Sources: src/ParsedMiddleware.php33-42


Usage Patterns

Direct Instantiation

Applications can create ParsedMiddleware instances directly to pre-parse middleware signatures:

$parsed = new ParsedMiddleware('auth:api,admin');
$name = $parsed->getName(); // 'auth'
$params = $parsed->getParameters(); // ['api', 'admin']

Sources: src/ParsedMiddleware.php13-16

Pipeline Integration

The more common usage pattern involves the pipeline automatically handling both ParsedMiddleware instances and raw strings:


Sources: src/Pipeline.php21-60

Container Resolution

Once parsed, the middleware name is resolved through the DI container in getPipeInstance() src/Pipeline.php72-86 The resolution process:

  1. Retrieves middleware instance from container using the parsed name
  2. Checks if instance implements MiddlewareInterface (PSR-15)
  3. If PSR-15, wraps in Psr15AdapterMiddleware and caches the adapted instance
  4. Returns the middleware instance ready for execution

Sources: src/Pipeline.php72-86


Performance Considerations

Parsing Overhead

The ParsedMiddleware constructor src/ParsedMiddleware.php13-16 performs parsing immediately upon instantiation. This design choice means:

  • Pre-parsed instances: When applications create ParsedMiddleware objects in advance (e.g., during application bootstrap), the parsing cost is paid once
  • String instances: When raw strings are passed to the pipeline, parsing occurs via parsePipeString() inherited from the base pipeline class, which happens during request processing

Caching Strategy

The Pipeline class caches resolved middleware instances but not ParsedMiddleware parsing results. Caching occurs at the adapted middleware level src/Pipeline.php77-82:

if ($middleware = ($this->adaptedMiddleware[$name] ?? null)) {
 return $middleware;
}

return $this->adaptedMiddleware[$name] = new Psr15AdapterMiddleware($pipe);

This means the parsing itself may occur multiple times across requests, but the more expensive adapter instantiation is cached.

Sources: src/Pipeline.php72-86 src/Pipeline.php14


Relationship to Base Pipeline

The Hypervel Pipeline extends Hyperf's BasePipeline src/Pipeline.php12 which provides a parsePipeString() method. The ParsedMiddleware class offers equivalent functionality but as a reusable object rather than a utility method.

Comparison

AspectparsePipeString()ParsedMiddleware
SourceInherited from Hyperf\Pipeline\PipelineHypervel-specific utility class
UsageCalled inline when processing stringsCan be instantiated in advance
Return TypeArray tuple [$name, $parameters]Object with getter methods
ReusabilitySingle-use parsingObject can be stored and reused
Type CheckingNot type-checkable in pipelineEnables instanceof checks in pipeline

The pipeline supports both approaches, checking for ParsedMiddleware instances first before falling back to string parsing src/Pipeline.php31-37

Sources: src/Pipeline.php9-12 src/Pipeline.php31-43