Skip to content

Conversation

@parsilver
Copy link
Contributor

Summary

This PR adds two major features to Transport PHP:

  • 🎯 Multipart/Form-Data File Upload - RFC 7578 compliant file upload support
  • 🍪 Cookie Management - RFC 6265 compliant automatic cookie handling

Both features are production-ready with comprehensive testing and documentation.


Feature 1: Multipart/Form-Data File Upload

New Components

  • src/Multipart/Part.php - Represents individual multipart form parts
  • src/Multipart/MultipartStreamBuilder.php - Builds RFC 7578 compliant multipart streams
  • tests/Multipart/MultipartTest.php - 25+ comprehensive tests
  • examples/file-upload.php - 7 practical usage examples

Capabilities

  • ✅ Mixed text fields and file uploads in single request
  • ✅ Multiple files support
  • ✅ Automatic content-type detection from file extensions
  • ✅ Custom boundaries, filenames, and content-types
  • ✅ Memory-efficient PSR-7 stream handling
  • ✅ Supports file paths, file contents, and PSR-7 streams

API Usage

// Simple file upload
$response = $transport->post('/upload')
    ->withFile('document', '/path/to/file.pdf', 'report.pdf')
    ->send();

// Multiple files with form data
$response = $transport->post('/upload')
    ->withMultipart([
        ['name' => 'title', 'contents' => 'My Upload'],
        ['name' => 'file', 'contents' => fopen('doc.pdf', 'r'), 'filename' => 'document.pdf']
    ])
    ->send();

// Advanced builder pattern
$builder = new MultipartStreamBuilder();
$builder->addField('username', 'john')
    ->addFile('avatar', '/path/to/avatar.jpg')
    ->addFileContents('data', $jsonData, 'data.json');

$response = $transport->post('/api/upload')
    ->withMultipartBuilder($builder)
    ->send();

Feature 2: Cookie Management

New Components

  • src/Cookie/Cookie.php - RFC 6265 compliant cookie class
  • src/Cookie/CookieJar.php - Cookie storage with domain/path matching
  • src/Middleware/CookieMiddleware.php - Automatic cookie handling
  • tests/Cookie/CookieTest.php - 33+ comprehensive tests
  • examples/cookie-session.php - 8 practical usage examples

Capabilities

  • ✅ Automatic cookie persistence across requests
  • ✅ RFC 6265 domain and path matching
  • ✅ Session vs persistent cookie handling
  • ✅ Secure/HttpOnly/SameSite attribute support
  • ✅ Cookie expiration handling
  • ✅ Export/Import for cookie persistence
  • ✅ Web scraping with session support

API Usage

// Automatic cookie handling
$transport = TransportBuilder::make()
    ->withCookies() // Enable automatic cookie management
    ->build();

// Login - cookies automatically stored
$transport->post('/login')
    ->withJson(['username' => 'user', 'password' => 'pass'])
    ->send();

// Subsequent requests automatically include cookies
$response = $transport->get('/profile')->send();

// Manual cookie management
$cookieJar = new CookieJar();
$cookieJar->setCookie(new Cookie(
    name: 'session_id',
    value: 'abc123',
    expiresAt: time() + 3600,
    domain: 'example.com',
    secure: true,
    httpOnly: true
));

$transport = TransportBuilder::make()
    ->withCookieJar($cookieJar)
    ->build();

Code Quality

Testing

  • 330 tests passing (55+ new tests added)
  • 648 assertions covering all functionality
  • ✅ Edge cases, error conditions, and happy paths tested
  • ✅ Real file operations tested with cleanup

Code Style

  • ✅ PSR-12 compliant
  • ✅ PHP 8.1+ strict types throughout
  • ✅ Full type safety with union types
  • ✅ Immutable builder patterns
  • ✅ Comprehensive PHPDoc comments

Documentation

  • ✅ README updated with feature documentation
  • ✅ 15 working examples across 2 files
  • ✅ Inline code documentation
  • ✅ Usage examples for common scenarios

Files Changed

New Files (9)

  • src/Multipart/Part.php
  • src/Multipart/MultipartStreamBuilder.php
  • src/Cookie/Cookie.php
  • src/Cookie/CookieJar.php
  • src/Middleware/CookieMiddleware.php
  • tests/Multipart/MultipartTest.php
  • tests/Cookie/CookieTest.php
  • examples/file-upload.php
  • examples/cookie-session.php

Modified Files (3)

  • src/RequestBuilder.php - Added multipart methods
  • src/TransportBuilder.php - Added cookie support
  • README.md - Added feature documentation

Stats

  • 12 files changed
  • 2,721 insertions
  • 0 deletions (fully backward compatible)

Breaking Changes

None - This PR is fully backward compatible with existing code.


Test Plan

  • All existing tests pass (330/330)
  • New multipart tests pass (25/25)
  • New cookie tests pass (33/33)
  • Code style checks pass (PSR-12)
  • Examples run successfully
  • No breaking changes to existing API

Use Cases

For API Clients

  • Upload profile pictures with metadata
  • Submit forms with file attachments
  • Build SDK clients with automatic cookie sessions

For Web Scraping

  • Maintain login sessions across requests
  • Handle authentication cookies automatically
  • Export/import cookies for session persistence

Implementation Notes

  • Both features follow official RFC specifications (RFC 7578, RFC 6265)
  • Cookie middleware integrates seamlessly with existing middleware stack
  • Multipart builder uses PSR-7 streams for memory efficiency
  • Thread-safe immutable configuration patterns maintained
  • Zero dependencies added (uses existing PSR interfaces)

Related Issues

Implements features requested for API client and web scraping use cases.


Checklist

  • Code follows PSR-12 style guidelines
  • All tests pass
  • New tests added for new features
  • Documentation updated
  • Examples provided
  • No breaking changes
  • Backward compatible

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)
@codecov
Copy link

codecov bot commented Oct 24, 2025

Codecov Report

❌ Patch coverage is 95.76471% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.41%. Comparing base (8ded390) to head (74d09ec).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/Cookie/Cookie.php 94.32% 8 Missing ⚠️
src/Multipart/MultipartStreamBuilder.php 92.75% 5 Missing ⚠️
src/Cookie/CookieJar.php 96.22% 4 Missing ⚠️
src/Multipart/Part.php 98.27% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main      #25      +/-   ##
============================================
- Coverage     96.74%   96.41%   -0.34%     
- Complexity      270      426     +156     
============================================
  Files            28       33       +5     
  Lines           830     1255     +425     
============================================
+ Hits            803     1210     +407     
- Misses           27       45      +18     

☔ 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.

Add comprehensive tests for previously untested or under-tested features:

- Add CookieMiddleware tests (0% → 100% coverage)
  - Cookie handling flow (adding to requests, extracting from responses)
  - Integration with CookieJar
  - Static factory methods and session persistence
  - HTTP/HTTPS secure cookie handling
  - Path and domain restrictions
  - Complete request-response cookie lifecycle

- Add RequestBuilder file upload tests (82.1% → 100% coverage)
  - Multipart form data with various formats
  - File upload with withFile() method
  - Custom filenames and additional form fields
  - MultipartStreamBuilder integration

- Add TransportBuilder cookie integration tests (91.8% → 100% coverage)
  - Cookie jar integration (withCookieJar, withCookies)
  - Automatic cookie handling across requests

- Add Multipart/Part edge case tests (77.3% → 97.7% coverage)
  - StreamInterface content size calculation
  - Content type guessing for various file extensions
  - Null filename handling
  - Header retrieval

- Add Cookie edge case tests (92.6% → 93.4% coverage)
  - Domain matching with null domain
  - Invalid URL handling
  - Expired cookie handling with includeExpired parameter

Total: 35 new tests, 73 new assertions
Overall coverage improved from 90.6% to 95.7% (+5.1%)
@parsilver parsilver self-assigned this Oct 24, 2025
@parsilver parsilver added the enhancement New feature or request label Oct 24, 2025
@parsilver parsilver merged commit 8705468 into main Oct 24, 2025
26 of 28 checks passed
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