Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Http Factory Implementation Laravel Package

psr-mock/http-factory-implementation

Lightweight PSR-17/PSR-7 HTTP factory/message mock implementation for PHP 8.1+. Built for SDKs and libraries to test against PSR interfaces without hard deps, with strict PSR compliance and helpful debugging API.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer (PHP 8.1+ required):

    composer require --dev psr-mock/http-factory-implementation:^1.0.1
    

    Ensure your project uses PSR-17 (HttpFactoryInterface) and PSR-7 (MessageInterface, StreamInterface) for HTTP messages.

  2. Basic Setup Import the factory and mock classes:

    use PsrMock\HttpFactory\MockHttpFactory;
    use PsrMock\HttpFactory\MockStream;
    
  3. First Use Case: Mocking HTTP Requests Create a mock HTTP factory and request in a test:

    $factory = new MockHttpFactory();
    $request = $factory->createRequest('GET', '/test');
    $request->withHeader('X-Custom-Header', 'value');
    

Implementation Patterns

Core Workflows

  1. Mocking HTTP Messages Use the factory to generate mock requests/responses with predefined headers, body, or status:

    $response = $factory->createResponse(200)
        ->withHeader('Content-Type', 'application/json')
        ->withBody($factory->createStreamFromString('{"key": "value"}'));
    
  2. Stream Mocking Simulate file uploads or binary responses:

    $stream = new MockStream('file contents');
    $request = $factory->createRequest('POST', '/upload')
        ->withBody($stream);
    
  3. Integration with Laravel Replace Laravel’s Symfony\Component\HttpFoundation or GuzzleHttp dependencies in tests:

    $this->app->instance(\Psr\Http\Message\RequestInterface::class, $factory->createRequest('GET', '/'));
    
  4. Dynamic Mocking Use closures for dynamic responses (e.g., based on request data):

    $factory->setResponseCallback(function ($request) {
        return $factory->createResponse(200)
            ->withBody($factory->createStreamFromString($request->getBody()->getContents()));
    });
    

Testing Patterns

  • Unit Testing Controllers Mock the HTTP factory to isolate logic:

    $request = $factory->createRequest('GET', '/api/data');
    $response = $this->app->handle($request);
    $this->assertEquals(200, $response->getStatusCode());
    
  • Mocking External APIs Replace HttpClient (e.g., Guzzle) with a mock factory:

    $client = new class($factory) implements \Psr\Http\Client\ClientInterface {
        public function sendRequest(RequestInterface $request) {
            return $this->factory->createResponse(200);
        }
    };
    

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement

    • Breaking Change: This package now requires PHP 8.1+. Update your project or use an older version (^1.0.0) if needed.
    • Verify compatibility with your test environment and CI/CD pipelines.
  2. Stream Behavior

    • Mock streams are in-memory by default. Use MockStream::fromFile() for file-based streams:
      $stream = MockStream::fromFile('/path/to/file');
      
    • Avoid reusing streams across tests; they may retain state.
  3. Header/Body Mutability

    • Methods like withHeader() return a new instance (immutable). Chain methods carefully:
      // Correct:
      $response = $factory->createResponse(200)
          ->withHeader('X-Test', '1')
          ->withHeader('X-Test', '2'); // Overwrites
      
  4. PSR Compliance

    • Ensure your tests expect PSR-7 interfaces (e.g., getBody() returns StreamInterface), not concrete classes.
  5. Laravel-Specific Quirks

    • If using Laravel’s Http facade, bind the mock factory to the container:
      $this->app->bind(\Psr\Http\Message\RequestFactoryInterface::class, function () use ($factory) {
          return $factory;
      });
      

Debugging Tips

  • Inspect Mocks Use var_dump($request->getHeaders()) or dd($response->getBody()->getContents()) to verify state.
  • Reset Factory State Recreate the factory for each test to avoid cross-contamination:
    $factory = new MockHttpFactory(); // Fresh instance per test
    

Extension Points

  1. Custom Mock Classes Extend MockHttpFactory or MockStream for domain-specific logic:

    class CustomStream extends MockStream {
        public function __toString() { return 'custom'; }
    }
    
  2. Middleware Testing Use the factory to simulate middleware behavior:

    $request = $factory->createRequest('GET', '/')
        ->withHeader('Authorization', 'Bearer token');
    $middleware = new AuthMiddleware();
    $response = $middleware->process($request, function () { return $factory->createResponse(200); });
    
  3. Performance For large-scale tests, pre-generate mocks and reuse them (but be mindful of state).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support