VOOZH about

URL: https://deepwiki.com/hypervel/router/4-middleware-system

⇱ Middleware System | hypervel/router | DeepWiki


Loading...
Menu

Middleware System

This document provides an overview of the middleware components included with the hypervel/router package. The middleware system handles request preprocessing, parameter binding, rate limiting, and URL signature validation within the routing pipeline. All middleware implement the PSR-15 MiddlewareInterface and integrate with Hyperf's middleware pipeline.

For detailed documentation of individual middleware components, see the child pages: Route Parameter Binding, Model Binding and UrlRoutable, Rate Limiting with ThrottleRequests, Signature Validation Middleware, and Middleware Configuration and Exclusions.

Sources: src/Middleware/SubstituteBindings.php26 src/Middleware/ThrottleRequests.php23 src/Middleware/ValidateSignature.php15

Architecture Overview

The middleware system consists of three core classes located in the Hypervel\Router\Middleware namespace:

Middleware ClassPrimary ResponsibilityKey Dependencies
SubstituteBindingsResolves route parameters to typed objectsRouter, RouteDependency, ContainerInterface
ThrottleRequestsEnforces rate limits on requestsRateLimiter (from hypervel/cache)
ValidateSignatureValidates cryptographic URL signaturesRequestContract

Each middleware implements Psr\Http\Server\MiddlewareInterface and processes requests through the process(ServerRequestInterface $request, RequestHandlerInterface $handler) method, following the PSR-15 standard.

Sources: src/Middleware/SubstituteBindings.php26-38 src/Middleware/ThrottleRequests.php23-43 src/Middleware/ValidateSignature.php15-32

Request Processing Pipeline

Middleware Execution Sequence


The middleware execute in sequence through the PSR-15 RequestHandlerInterface, with each middleware deciding whether to continue the chain by calling $handler->handle($request) or to throw an exception to halt processing.

Sources: src/Middleware/ThrottleRequests.php61-156 src/Middleware/ValidateSignature.php56-65 src/Middleware/SubstituteBindings.php40-57

Middleware Class Details

SubstituteBindings

The SubstituteBindings class performs automatic parameter resolution by converting route parameter strings into typed objects based on controller method signatures.

Class Structure


The middleware accesses the Dispatched attribute from the request src/Middleware/SubstituteBindings.php43 and modifies its params property with resolved objects src/Middleware/SubstituteBindings.php54

Parameter Resolution Priority

  1. Explicit Bindings: Router::getExplicitBinding($name) returns a closure if registered src/Middleware/SubstituteBindings.php86-88
  2. Model Bindings: Router::getModelBinding($name) returns a class name if registered src/Middleware/SubstituteBindings.php104-105
  3. Type-based Resolution: Uses RouteDependency reflection to determine parameter types src/Middleware/SubstituteBindings.php62-73

Resolution Strategies by Type

Type CheckInterface/ClassResolution MethodLine Reference
is_a($class, UrlRoutable::class, true)Hypervel\Router\Contracts\UrlRoutableresolveUrlRoutable()src/Middleware/SubstituteBindings.php107-109
is_a($class, Model::class, true)Hyperf\Database\Model\ModelresolveModel()src/Middleware/SubstituteBindings.php111-113
is_a($class, BackedEnum::class, true)BackedEnumresolveBackedEnum()src/Middleware/SubstituteBindings.php115-117

Sources: src/Middleware/SubstituteBindings.php26-163

ThrottleRequests

The ThrottleRequests class implements rate limiting using the Hypervel\Cache\RateLimiter service.

Configuration Methods

Static MethodSignaturePurposeExample
using()using(string $name): stringNamed rate limiterThrottleRequests::using('api')
with()with(int $maxAttempts, int $decayMinutes, string $prefix): stringDirect configurationThrottleRequests::with(60, 1)

Both methods return a string for middleware configuration src/Middleware/ThrottleRequests.php48-59

Request Processing Flow

The process() method accepts parameters: $maxAttempts, $decayMinutes, and $prefix src/Middleware/ThrottleRequests.php61-67 It distinguishes between named limiters and direct configuration:

Rate Limiting Logic


The middleware calls limiter->tooManyAttempts($limit->key, $limit->maxAttempts) src/Middleware/ThrottleRequests.php138 and throws a ThrottleRequestsException if the limit is exceeded src/Middleware/ThrottleRequests.php139 Otherwise, it increments the counter with limiter->hit() src/Middleware/ThrottleRequests.php142 and adds rate limit headers to the response src/Middleware/ThrottleRequests.php148-153

Response Headers

The middleware adds standard rate limit headers: X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After, and X-RateLimit-Reset src/Middleware/ThrottleRequests.php258-268

Sources: src/Middleware/ThrottleRequests.php23-318

ValidateSignature

The ValidateSignature class validates URL signatures using the RequestContract::hasValidSignatureWhileIgnoring() method.

Configuration Methods

Static MethodPurposeReturns
relative()Validate relative URL signatures'ValidateSignature:relative,...'
absolute()Validate absolute URL signatures'ValidateSignature' or 'ValidateSignature:...'
except()Globally ignore parametersvoid (modifies static $neverValidate)

The relative() and absolute() methods return middleware configuration strings src/Middleware/ValidateSignature.php37-54 while except() adds parameters to the global exclusion list src/Middleware/ValidateSignature.php86-91

Validation Process

The middleware parses arguments to determine validation mode src/Middleware/ValidateSignature.php70-81 and calls request->hasValidSignatureWhileIgnoring($ignore, !$relative) src/Middleware/ValidateSignature.php60 If validation fails, it throws an InvalidSignatureException with a 403 status code src/Middleware/ValidateSignature.php64

Sources: src/Middleware/ValidateSignature.php15-92 src/Exceptions/InvalidSignatureException.php9-18

Dependency Injection and Service Integration

Middleware Constructor Dependencies


Key Integration Points

MiddlewareDependencyUsageCode Reference
SubstituteBindingsRouterRetrieves explicit/model bindings via getExplicitBinding(), getModelBinding()src/Middleware/SubstituteBindings.php86 src/Middleware/SubstituteBindings.php104
SubstituteBindingsRouteDependencyAnalyzes method signatures via getMethodDefinitions(), getClosureDefinitions()src/Middleware/SubstituteBindings.php65 src/Middleware/SubstituteBindings.php72
SubstituteBindingsDispatchedAccesses and modifies route parameters via getAttribute(Dispatched::class)src/Middleware/SubstituteBindings.php43
ThrottleRequestsRateLimiterChecks limits and increments counters via tooManyAttempts(), hit(), retriesLeft()src/Middleware/ThrottleRequests.php138 src/Middleware/ThrottleRequests.php142 src/Middleware/ThrottleRequests.php276
ValidateSignatureRequestContractValidates signatures via hasValidSignatureWhileIgnoring()src/Middleware/ValidateSignature.php60

Sources: src/Middleware/SubstituteBindings.php33-38 src/Middleware/ThrottleRequests.php40-43 src/Middleware/ValidateSignature.php29-32

Exception Handling

Exception Types and Conditions

Exception ClassNamespaceThrown ByTrigger ConditionHTTP StatusCode Reference
ModelNotFoundExceptionHyperf\Database\ModelresolveModel()Model::firstOrFail() returns no results404src/Middleware/SubstituteBindings.php146
BackedEnumCaseNotFoundExceptionHypervel\Router\ExceptionsresolveBackedEnum()BackedEnum::tryFrom() returns null404src/Middleware/SubstituteBindings.php158
UrlRoutableNotFoundExceptionHypervel\Router\ExceptionsresolveUrlRoutable()resolveRouteBinding() returns null404src/Middleware/SubstituteBindings.php132
ThrottleRequestsExceptionHypervel\HttpMessage\ExceptionsbuildException()limiter->tooManyAttempts() returns true429src/Middleware/ThrottleRequests.php214
InvalidSignatureExceptionHypervel\Router\Exceptionsprocess()hasValidSignatureWhileIgnoring() returns false403src/Middleware/ValidateSignature.php64 src/Exceptions/InvalidSignatureException.php16

Exception Flow in SubstituteBindings

The SubstituteBindings middleware declares these exceptions in its @throws annotations src/Middleware/SubstituteBindings.php99-100 but allows them to propagate to the framework's exception handler, which converts them to appropriate HTTP responses.

Sources: src/Middleware/SubstituteBindings.php99-100 src/Middleware/SubstituteBindings.php132 src/Middleware/SubstituteBindings.php146 src/Middleware/SubstituteBindings.php158 src/Middleware/ThrottleRequests.php139 src/Middleware/ThrottleRequests.php214 src/Middleware/ValidateSignature.php64 src/Exceptions/InvalidSignatureException.php9-18

Configuration and Usage

The middleware components are designed to be configured through static factory methods and integrated into route definitions or global middleware stacks:

  • Route-specific: Applied to individual routes or route groups
  • Global: Applied to all routes through the middleware pipeline
  • Conditional: Applied based on route patterns or request characteristics

For detailed configuration examples and advanced usage patterns, see the individual middleware documentation pages: Route Parameter Binding, Rate Limiting, and Signature Validation.

Sources: src/Middleware/ThrottleRequests.php47-59 src/Middleware/ValidateSignature.php37-54