VOOZH about

URL: https://deepwiki.com/hypervel/components/3.4-url-generation-and-signed-urls

⇱ URL Generation and Signed URLs | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

URL Generation and Signed URLs

Purpose and Scope

This document describes the URL generation system in Hypervel, which provides utilities for generating application URLs, named route URLs, asset URLs, and cryptographically signed URLs. The system is implemented through the UrlGenerator class and provides coroutine-safe URL generation with caching strategies, origin override capabilities for multi-tenancy, and comprehensive signed URL support.

For information about route registration and matching, see Routing and Dispatching. For middleware-based signature validation, see Middleware Pipeline.


UrlGenerator Class

The UrlGenerator class (src/router/src/UrlGenerator.php28-519) implements the UrlGeneratorContract interface and serves as the central URL generation facility. It is registered in the dependency injection container and can be accessed via the URL facade or helper functions.

Key Components

ComponentTypePurpose
ContainerInterfaceDependencyResolves router, request, config, and session instances
DispatcherFactoryDependencyProvides access to named route definitions
formatHostUsingClosureOptional callback to format host portions of URLs
formatPathUsingClosureOptional callback to format path portions of URLs
signedKeystringKey used for signing URLs (defaults to app.key config)
cachedSchemestringCached request scheme for performance
forceSchemestringForced scheme override for all generated URLs

Sources: src/router/src/UrlGenerator.php28-61


Basic URL Generation

Application URLs

The to() method generates absolute or relative URLs to application paths:


Behavior:

  • Returns the path unchanged if it's already a valid URL (http://, https://, //, mailto:, tel:, sms:, #)
  • Extracts and preserves query strings from the path
  • Appends $extra parameters as path segments with URL encoding
  • Determines scheme from $secure parameter, forced scheme, or request context
  • Caches the root URL in coroutine Context for performance

Sources: src/router/src/UrlGenerator.php105-120 tests/Router/UrlGeneratorTest.php111-121

URL Generation Flow Diagram


Sources: src/router/src/UrlGenerator.php105-120 src/router/src/UrlGenerator.php487-509

Secure URLs

The secure() method forces HTTPS scheme:


Sources: src/router/src/UrlGenerator.php139-142

Asset URLs

The asset() method generates URLs to static assets:


Unlike to(), this method does not append trailing slashes and is intended for static files (CSS, JavaScript, images). The secureAsset() method forces HTTPS for assets.

Sources: src/router/src/UrlGenerator.php147-156 src/router/src/UrlGenerator.php161-164

Query String URLs

The query() method generates URLs with merged query parameters:


This method:

  1. Extracts existing query string from path
  2. Parses existing parameters
  3. Merges with provided $query array
  4. Generates final URL with combined parameters

Sources: src/router/src/UrlGenerator.php125-134 tests/Router/UrlGeneratorTest.php169-183


Named Route URLs

The route() method generates URLs to named routes by resolving route parameters and building the URL from route definitions:


Route URL Resolution Process


Sources: src/router/src/UrlGenerator.php68-100 tests/Router/UrlGeneratorTest.php59-92

Route Parameter Handling

Route definitions are stored as arrays of segments. Dynamic segments are arrays containing the parameter name and regex pattern:


The route() method iterates through segments, replacing parameter placeholders with values from $parameters and removing used parameters. Remaining parameters are appended as query string.

Sources: src/router/src/UrlGenerator.php76-88 tests/Router/UrlGeneratorTest.php73-79

UrlRoutable Interface

Objects implementing UrlRoutable can be passed as route parameters and will be automatically converted to their route key:


The formatParameters() method handles this conversion.

Sources: src/router/src/UrlGenerator.php454-463 src/router/src/Contracts/UrlRoutable.php


Signed URLs

Signed URLs contain cryptographic signatures that verify the URL has not been tampered with. They are useful for temporary access links, email verification, and other security-sensitive scenarios.

Creating Signed URLs


Process:

  1. Validates parameters don't use reserved names (signature, expires)
  2. Adds expiration timestamp if provided
  3. Sorts parameters alphabetically (for consistent signature)
  4. Generates signature using HMAC-SHA256
  5. Appends signature to URL as query parameter

The signature is computed as:

signature = hash_hmac('sha256', full_url_without_signature, app_key)

Sources: src/router/src/UrlGenerator.php197-216 tests/Router/UrlGeneratorTest.php452-481

Signed URL Creation Flow


Sources: src/router/src/UrlGenerator.php197-216

Temporary Signed URLs

The temporarySignedRoute() method is a convenience wrapper that ensures an expiration is set:


Sources: src/router/src/UrlGenerator.php239-242

Validating Signed URLs

Three methods validate signed URLs:

MethodPurpose
hasValidSignature()Validates signature and expiration for absolute URLs
hasValidRelativeSignature()Validates signature and expiration for relative URLs
hasCorrectSignature()Validates signature only (ignores expiration)
signatureHasNotExpired()Validates expiration only

Validation Process:


Sources: src/router/src/UrlGenerator.php247-260

Signature Verification Algorithm


Sources: src/router/src/UrlGenerator.php264-295

Reserved Parameter Names

The parameters signature and expires are reserved and cannot be used as route parameters in signed URLs. The ensureSignedRouteParametersAreNotReserved() method enforces this:

Sources: src/router/src/UrlGenerator.php221-234 tests/Router/UrlGeneratorTest.php514-556

Signed Key Configuration

The signing key defaults to app.key configuration value but can be overridden:


Sources: src/router/src/UrlGenerator.php447-452 src/router/src/UrlGenerator.php477-485


URL Formatting and Customization

Scheme Control

Multiple methods control URL schemes:

MethodPurpose
formatScheme(?bool $secure)Determines scheme based on parameter or request
forceScheme(?string $scheme)Forces specific scheme for all URLs
forceHttps(bool $force)Convenience method to force HTTPS

Scheme Resolution Priority:

  1. Explicit $secure parameter in URL generation methods
  2. Forced scheme via forceScheme()
  3. Cached scheme from current request
  4. Request URI scheme

Sources: src/router/src/UrlGenerator.php179-190 src/router/src/UrlGenerator.php390-405 tests/Router/UrlGeneratorTest.php373-437

Custom Formatters

Two callbacks allow custom URL formatting:


These callbacks are applied in the format() method:


Use Cases:

  • Adding subdomain prefixes
  • Modifying paths for localization
  • CDN URL generation
  • Multi-tenant path prefixing

Sources: src/router/src/UrlGenerator.php358-371 src/router/src/UrlGenerator.php427-442 tests/Router/UrlGeneratorTest.php196-239


Origin Override for Multi-Tenancy

The useOrigin() method allows runtime override of the base URL, essential for multi-tenant applications where different tenants may use different domains:


Origin Override Mechanism


Sources: src/router/src/UrlGenerator.php412-422 tests/Router/UrlGeneratorTest.php558-607

Implementation Details

The forced origin is stored in coroutine Context at key __url.forced_root:


The getRootUrl() method checks for forced origin first:


Key Points:

  • Origin override is stored in coroutine Context for request isolation
  • Passing null clears the override
  • Cache is cleared when origin is changed
  • Scheme from URL generation method still applies (HTTP vs HTTPS)
  • Affects all URL generation methods: to(), route(), asset()

Sources: src/router/src/UrlGenerator.php412-422 src/router/src/UrlGenerator.php487-509


URL Caching Strategy

The URL generator employs a two-level caching strategy in coroutine Context:

Cache Keys and Purpose

Context KeyPurposeLifecycle
__request.root.uriCached root URL from requestPer-request
__url.forced_rootForced origin overrideSet by useOrigin()
SessionInterface::classSession for previous URLPer-request

Caching Flow


Sources: src/router/src/UrlGenerator.php487-509

Cache Invalidation

The cache is cleared in two scenarios:

  1. Origin Override Change: When useOrigin() is called, __request.root.uri is destroyed to force recalculation
  2. Request Context Cleared: When coroutine completes, Context is cleared automatically

Sources: src/router/src/UrlGenerator.php412-422 tests/Router/UrlGeneratorTest.php623-639

Scheme Caching

The URL scheme is also cached in the $cachedScheme property:


This cache is cleared when forceScheme() is called.

Sources: src/router/src/UrlGenerator.php179-190 src/router/src/UrlGenerator.php390-395


Helper Functions and Facades

Global Helper Functions

Four helper functions provide convenient access to URL generation:

FunctionDefined InPurpose
route()src/foundation/src/helpers.php680-690Generate named route URL
url()src/foundation/src/helpers.php692-700Generate application URL or return generator instance
secure_url()src/foundation/src/helpers.php702-710Generate secure (HTTPS) URL
asset()src/foundation/src/helpers.php712-720Generate asset URL

These functions delegate to the router package's functions:

Sources: src/router/src/Functions.php1-49 src/foundation/src/helpers.php680-720

URL Facade

The URL facade (src/support/src/Facades/URL.php1-49) provides static access to all UrlGenerator methods:


Sources: src/support/src/Facades/URL.php1-49

Helper Function Usage Patterns


Sources: src/router/src/Functions.php24-32 src/foundation/src/helpers.php692-700


Integration with Request Context

Current and Previous URLs

Methods for retrieving current and previous request URLs:


Previous URL Resolution


Sources: src/router/src/UrlGenerator.php316-340 src/router/src/UrlGenerator.php345-353

Session Integration

The previous URL is retrieved from session using SessionInterface::previousUrl():


Sources: src/router/src/UrlGenerator.php345-353


Code Entity Reference

Class Methods and Their Purposes

MethodReturn TypePrimary Use Case
route()stringNamed route URL generation
to()stringBasic application URL generation
query()stringURL with merged query parameters
secure()stringForce HTTPS URLs
asset()stringStatic asset URLs
secureAsset()stringHTTPS asset URLs
signedRoute()stringCryptographically signed URLs
temporarySignedRoute()stringTime-limited signed URLs
hasValidSignature()boolValidate signed URL requests
hasCorrectSignature()boolValidate signature only
signatureHasNotExpired()boolValidate expiration only
full()stringCurrent full URL
current()stringCurrent URL without query
previous()stringPrevious request URL
previousPath()stringPrevious request path
forceScheme()voidOverride URL scheme
forceHttps()voidForce HTTPS scheme
useOrigin()voidOverride base URL for multi-tenancy
formatHostUsing()staticCustom host formatting
formatPathUsing()staticCustom path formatting
setSignedKey()staticSet signing key
format()stringCombine root and path
formatScheme()stringDetermine URL scheme
isValidUrl()boolCheck if path is already valid URL

Sources: src/router/src/Contracts/UrlGenerator.php1-152 src/router/src/UrlGenerator.php28-519

Refresh this wiki

On this page