VOOZH about

URL: https://deepwiki.com/hypervel/api-client/6.3-type-safety

⇱ Type Safety | hypervel/api-client | DeepWiki


Loading...
Menu

Type Safety

Purpose and Scope

This document explains the generic type system used throughout the hypervel/api-client package to provide compile-time type safety and enhanced IDE support. It covers the PHP template annotations, how to specify custom resource classes, and the benefits of type-safe API responses.

For information about accessing response data through the resource interface, see Accessing Response Data. For details on response transformation methods, see Response Transformation.


Generic Type System Overview

The API client uses PHP's PHPDoc template annotations to implement a generic type system. While PHP does not have native generics at runtime, these annotations enable static analysis tools and IDEs to provide type checking and autocomplete functionality.

The system employs two primary type parameters:

Type ParameterUsage LocationPurpose
TConfigApiClientSpecifies the configuration object type (must extend DataObject)
TResourceApiClient, PendingRequestSpecifies the resource class returned by API requests

Sources: src/ApiClient.php10-11 src/PendingRequest.php19


Type Parameter Declaration

ApiClient Type Parameters

The ApiClient class declares two generic type parameters that define the contract for configuration and response types:

@template TConfig of DataObject
@template TResource of ApiResource

The TConfig parameter constrains the configuration type to subclasses of DataObject, while TResource constrains the response type to subclasses of ApiResource. The class also declares itself as a mixin of PendingRequest<TResource>, enabling transparent method delegation while preserving type information.

Declaration Structure:

ElementTypeLocationDescription
$confignull|TConfigPropertyHolds the configuration object instance
$resourceclass-string<TResource>PropertyStores the fully-qualified class name of the resource
getConfig()null|TConfigMethodReturns the typed configuration object

Sources: src/ApiClient.php10-24 src/ApiClient.php50-54

PendingRequest Type Parameters

The PendingRequest class declares a single type parameter that propagates through all request methods:

@template TResource of ApiResource

This parameter is used consistently across all HTTP method declarations (get(), post(), put(), patch(), delete(), head(), send()) to ensure the return type matches the configured resource class.

Sources: src/PendingRequest.php19 src/PendingRequest.php27-29


Type Flow Through Request Lifecycle

The following diagram illustrates how generic type parameters flow through the request execution lifecycle:

Type Parameter Propagation Flow


Sources: src/ApiClient.php10-14 src/PendingRequest.php19-29 src/PendingRequest.php175-244 src/PendingRequest.php265-291


Specifying Custom Resource Classes

The withResource() Method

The withResource() method allows you to override the default ApiResource class with a custom implementation. This method performs validation to ensure type safety:

Validation Rules:

CheckError ConditionException Message
Class existence!class_exists($resource)Resource class {name} does not exist
Inheritance!is_subclass_of($resource, ApiResource::class)Resource class {name} must be a subclass of ApiResource

The method signature uses class-string<TResource> to constrain the parameter to valid class names:


Sources: src/PendingRequest.php145-167

Resource Class Mapping


Sources: src/PendingRequest.php150-167 src/PendingRequest.php265-291 src/ApiResource.php1-147


HTTP Method Return Types

All HTTP methods in PendingRequest are annotated with @return TResource to ensure type consistency:

Type-Safe Method Signatures:

MethodSignatureReturn Type AnnotationLine Reference
get()get(string $url, ...)@return TResource172-178
head()head(string $url, ...)@return TResource183-189
post()post(string $url, ...)@return TResource194-200
patch()patch(string $url, ...)@return TResource205-211
put()put(string $url, ...)@return TResource216-222
delete()delete(string $url, ...)@return TResource227-233
send()send(string $method, ...)@return TResource238-244

The internal sendRequest() method creates the resource instance using the configured class:


This line at src/PendingRequest.php290 dynamically invokes the static make() method on the configured resource class, returning an instance of type TResource.

Sources: src/PendingRequest.php170-244 src/PendingRequest.php290


Static Analysis and IDE Integration

Code Entity to Type Mapping


Sources: src/PendingRequest.php19 src/PendingRequest.php147 src/PendingRequest.php172-238 src/ApiClient.php10-11

Type Safety Benefits

Compile-Time Guarantees:

BenefitDescriptionImpact
Type CheckingStatic analyzers validate that returned resources match declared typesCatches type errors before runtime
AutocompleteIDEs can suggest properties and methods specific to the custom resource classImproved developer productivity
RefactoringRenaming resource properties/methods updates all usagesSafer codebase evolution
DocumentationPHPDoc annotations serve as inline documentationBetter code comprehension

Runtime Validation:

The withResource() method provides runtime validation that complements static analysis:

  1. Class Existence Check - Verifies the class name is valid at src/PendingRequest.php152-156
  2. Inheritance Check - Ensures the class extends ApiResource at src/PendingRequest.php158-162
  3. Exception Throwing - Fails fast with descriptive error messages

Sources: src/PendingRequest.php150-167


Mixin Type Declarations

The @mixin annotation enables transparent method delegation while preserving type information:

ApiClient Mixin Declaration:


This declaration at src/ApiClient.php10-14 tells static analyzers that ApiClient forwards method calls to PendingRequest<TResource>, allowing methods like get(), post(), etc., to be called directly on the client instance while maintaining type safety.

ApiResource Mixin Declaration:


This declaration at src/ApiResource.php16-18 enables ApiResource instances to forward method calls to the wrapped ApiResponse object, providing access to response methods like status(), header(), and json().

Sources: src/ApiClient.php10-14 src/ApiResource.php16-18


Type-Safe Resource Instantiation

Resource Factory Pattern

The ApiResource::make() static method serves as a factory for creating typed resource instances:


The static return type ensures that when called on a subclass (e.g., UserResource::make()), the return type is correctly inferred as UserResource rather than the base ApiResource class. This is crucial for maintaining type safety through the inheritance hierarchy.

Instantiation Flow:


Sources: src/PendingRequest.php290 src/ApiResource.php84-90


Class-String Type Constraint

The class-string<T> type annotation provides additional type safety for class name strings:

Property Declaration:


This declaration at src/PendingRequest.php27-29 constrains the $resource property to contain only valid class names of classes that extend or implement TResource. Static analyzers can verify that:

  1. The string value represents an actual class
  2. The class is compatible with the TResource type constraint
  3. Operations like new $resource() are type-safe

Method Parameter:


This parameter annotation at src/PendingRequest.php147 ensures that only valid resource class names can be passed to the method.

Sources: src/PendingRequest.php27-29 src/PendingRequest.php147 src/ApiClient.php22-24


Type Parameter Inheritance Flow


Sources: src/ApiClient.php22-24 src/ApiClient.php112-114 src/PendingRequest.php53-62 src/PendingRequest.php265-291 src/ApiResource.php87-89


Summary

The type safety system in hypervel/api-client provides compile-time guarantees through PHPDoc template annotations while maintaining runtime validation. The key components are:

  • Generic Type Parameters: TConfig and TResource enable customization while preserving type information
  • Type Flow: Types propagate from ApiClient through PendingRequest to the final resource instance
  • Runtime Validation: The withResource() method validates class existence and inheritance
  • Static Analysis: PHPDoc annotations enable IDE autocomplete and static type checking
  • Factory Pattern: The make() method with static return type preserves subclass types

This architecture ensures that custom resource classes maintain full type safety throughout the request lifecycle.