Skip to content

Conversation

@parsilver
Copy link
Contributor

Summary

This PR introduces version 2 of the Transport library with a complete architectural redesign. The new version features a middleware pipeline architecture, fluent API for building requests, and advanced retry strategies with exponential backoff.

Key Features

Middleware Architecture - Extensible plugin system for custom behavior

  • LoggingMiddleware for request/response logging
  • TimeoutMiddleware for request timeouts
  • RetryMiddleware with intelligent retry logic
  • Support for custom middleware via MiddlewareInterface

Fluent Request Builder - Chainable API for building requests

  • Method chaining for headers, query params, body, etc.
  • JSON and form data helpers
  • Authentication helpers (Bearer token, Basic auth)

Advanced Retry Strategies

  • ExponentialBackoffStrategy with jitter support
  • FixedDelayStrategy for simple retries
  • RetryCondition for intelligent retry decisions
  • Comprehensive retry context tracking

Immutable Configuration - Thread-safe, predictable behavior

  • TransportConfig for centralized configuration
  • Configuration set during build phase
  • No mutable setters

Enhanced Exception Handling

  • NetworkException for network-related errors
  • TimeoutException with timeout context
  • JsonParseException with detailed error info
  • RetryExhaustedException with full retry history

Improved Response Interface

  • json() method with dot notation support
  • jsonOrNull() for safe JSON parsing
  • toArray() for array conversion
  • Enhanced error handling

Changes

Added:

  • Middleware system (MiddlewareInterface, MiddlewareStack)
  • RequestBuilder for fluent API
  • TransportConfig for immutable configuration
  • Retry strategies (ExponentialBackoffStrategy, FixedDelayStrategy)
  • RetryContext and RetryCondition
  • New exception classes (NetworkException, TimeoutException, JsonParseException, RetryExhaustedException)
  • Comprehensive test coverage

Modified:

  • Transport and TransportBuilder refactored for middleware support
  • ResponseInterface enhanced with new methods
  • Response implementation with improved JSON handling
  • Updated README with extensive examples

Removed:

  • ClientInterface and RequestInterface (replaced by PSR interfaces directly)
  • Old Request class (replaced by RequestBuilder)
  • ResponseFactory (functionality moved to ResponseBuilder)
  • Deprecated traits (PsrRequestTrait, PsrResponseTrait)
  • Old exception classes (ClientException, MaxRetriesExceededException)

Breaking Changes

⚠️ Configuration is now immutable

  • Configuration must be set during TransportBuilder build phase
  • No mutable setters available after build

⚠️ Interface changes

  • ClientInterface removed, uses PSR-18 directly
  • RequestInterface removed, uses PSR-7 directly
  • Response methods renamed (isSuccessfull()isSuccessful())

Migration Guide

Before (v1):

$transport = new Transport();
$transport->setTimeout(30);
$response = $transport->get('https://api.example.com/users');

After (v2):

$transport = TransportBuilder::make()
    ->withBaseUri('https://api.example.com')
    ->withTimeout(30)
    ->build();
$response = $transport->get('/users')->send();

Test Plan

  • All existing tests updated and passing
  • New middleware tests added
  • Retry strategy tests added
  • Request builder tests added
  • Exception handling tests added
  • JSON parsing tests added
  • Integration tests updated

Stats

  • 41 files changed
  • 2,805 insertions(+)
  • 934 deletions(-)
  • Net +1,871 lines

Documentation

  • Comprehensive README with usage examples
  • Architecture documentation
  • Migration guide included
  • Code examples for all major features

Major architectural improvements:
- Introduce middleware pipeline architecture (LoggingMiddleware, TimeoutMiddleware, RetryMiddleware)
- Implement fluent RequestBuilder API for chainable request construction
- Add advanced retry strategies with exponential backoff and jitter
- Create comprehensive exception hierarchy (NetworkException, TimeoutException, JsonParseException, etc.)
- Add immutable TransportConfig for thread-safe configuration
- Implement RetryContext and RetryCondition for intelligent retry logic
- Enhance ResponseInterface with json(), jsonOrNull(), and toArray() methods
- Remove deprecated ClientInterface, RequestInterface, and related traits
- Update to Pest v2 for testing
- Comprehensive README with usage examples and architecture documentation

Breaking changes:
- Configuration is now immutable and set during build phase
- Removed mutable setters in favor of builder pattern
- Changed ClientInterface to use PSR-18 directly
- Update pestphp/pest from ^2.0 to ^2.30 to fix --prefer-lowest test failures
  * Resolves "Call to undefined function describe()" error
  * Ensures describe() function is available in all test scenarios
- Migrate PHPUnit XML configuration to latest schema (10.5)
  * Removes deprecated schema warning
  * Updates to modern PHPUnit configuration format
- Add .phpunit.cache to .gitignore for PHPUnit 10.5 cache directory

All tests passing: 75 passed (133 assertions)
@codecov
Copy link

codecov bot commented Oct 24, 2025

Codecov Report

❌ Patch coverage is 96.46134% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.74%. Comparing base (48a120f) to head (8834173).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
src/Factory/ClientFactory.php 50.00% 23 Missing ⚠️
src/Response.php 96.07% 2 Missing ⚠️
src/Middleware/RetryMiddleware.php 96.00% 1 Missing ⚠️
src/Transport.php 98.07% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##               main      #24       +/-   ##
=============================================
+ Coverage     83.88%   96.74%   +12.86%     
- Complexity      101      270      +169     
=============================================
  Files             9       28       +19     
  Lines           242      830      +588     
=============================================
+ Hits            203      803      +600     
+ Misses           39       27       -12     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

parsilver and others added 3 commits October 24, 2025 12:15
…nability

Implement comprehensive serialization layer using Strategy, Factory, and
Dependency Injection patterns to improve code quality, performance, and
extensibility.

Key Features:
- Modern PHP 8.1+ JSON error handling with JSON_THROW_ON_ERROR
- Performance-optimized flags (UNESCAPED_SLASHES, UNESCAPED_UNICODE)
- Protection against integer overflow (JSON_BIGINT_AS_STRING)
- Configurable depth limits to prevent stack overflow
- Enhanced exception hierarchy with detailed error information
- 100% backward compatible with existing API

New Components:
- SerializerInterface: Strategy pattern for swappable serialization formats
- JsonConfig: Immutable configuration object with fluent API
- JsonSerializer: High-performance JSON encoder/decoder
- SerializerFactory: Factory pattern for creating serializers
- SerializationException: Base exception with metadata
- JsonEncodeException: Encoding-specific exception with context

Enhanced Existing Components:
- Response: Injected serializer via dependency injection
- RequestBuilder: Uses serializer for JSON encoding with error handling
- JsonParseException: Extended with depth and size information
- MockHttpClient: Consistent serializer usage in tests

Design Patterns:
- Strategy Pattern: Swappable serialization formats
- Factory Pattern: Centralized serializer creation
- Dependency Injection: Loose coupling, easy testing
- Configuration Object: Immutable, fluent configuration
- Template Method: Consistent exception hierarchy

Performance Improvements:
- Modern JSON flags reduce output size ~10%
- Automatic integer overflow protection
- Configurable depth limits prevent stack overflow
- Preserved caching mechanism for repeated calls

Testing:
- 50 new comprehensive tests (JsonConfig, JsonSerializer, SerializerFactory)
- All 125 tests passing with 100% backward compatibility
- Edge cases covered: deep nesting, large integers, invalid JSON

Future Extensions:
- Easy to add XML, MessagePack, or other serialization formats
- Custom serializers can be registered at runtime
- Open/Closed principle allows extension without modification
- Implement ClientFactory with auto-detection for Symfony and Guzzle HTTP clients
- Add HttpFactory for PSR-7/PSR-17 object creation
- Create new exception classes: BadResponseException, ClientException, ServerException, HttpException
- Refactor ResponseExceptionFactory with improved error message extraction
- Update README with Quick Start guide and HTTP client selection documentation
- Add examples directory with usage examples
- Update composer.json to move Guzzle to dev dependencies and add symfony/http-client
- Update tests to use new exception classes
@parsilver parsilver added the enhancement New feature or request label Oct 24, 2025
parsilver and others added 3 commits October 24, 2025 12:55
- Add extensive PSR-7 Response implementation tests
- Add middleware stack tests for push operations and empty stacks
- Add new test files for exceptions, factory, and transport config
- Apply code style improvements across example files (single quotes, parentheses removal)
- Clean up trailing whitespace in ResponseExceptionFactory
- Change Response::$jsonDecoded type from ?array to mixed to properly handle non-array JSON (objects, scalars, etc.)
- Add comprehensive test coverage for StreamInterface body handling
- Add tests for non-array JSON responses and scalar value extraction
- Add tests for Transport and TransportBuilder getters and configuration
- Add tests for retry conditions and JSON config validation
- Improve test coverage for edge cases in serialization and response handling
@parsilver parsilver merged commit fc9e805 into main Oct 24, 2025
28 checks passed
parsilver added a commit that referenced this pull request Oct 24, 2025
This commit introduces two major features for Transport PHP:

## Feature 1: Multipart/Form-Data File Upload

- Add `Part` class for representing multipart form components
- Add `MultipartStreamBuilder` for RFC 7578 compliant multipart streams
- Add `withMultipart()`, `withFile()`, and `withMultipartBuilder()` methods to RequestBuilder
- Support for mixed text fields and file uploads in single request
- Automatic content-type detection based on file extensions
- Custom boundaries, filenames, and content-types support
- PSR-7 StreamInterface compliance for memory-efficient operations

## Feature 2: Cookie Management

- Add `Cookie` class with RFC 6265 compliance
- Add `CookieJar` for cookie storage with domain/path matching
- Add `CookieMiddleware` for automatic cookie handling
- Add `withCookies()` and `withCookieJar()` methods to TransportBuilder
- Support for session and persistent cookies
- Automatic cookie expiration handling
- Cookie export/import for persistence
- Secure/HttpOnly/SameSite attribute support
- Proper domain and path matching algorithms

## Testing & Quality

- Add comprehensive test suite (55+ new tests, 330 total passing)
- Add practical examples (file-upload.php, cookie-session.php)
- Update README with feature documentation and usage examples
- PSR-12 code style compliance
- Full type safety with PHP 8.1+ strict types

## Breaking Changes

None - fully backward compatible with existing code.

Closes #24 (if applicable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants