Weave Code
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

Phiremock Server Laravel Package

mcustiel/phiremock-server

PHP HTTP mock/stub server inspired by WireMock. Mock requests by method/headers/URL/body/forms, set responses via REST API, support scenarios, priorities, latency simulation, verification counts, proxying, and loading expectations from JSON files.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (dev dependency):
    composer require-dev mcustiel/phiremock-server guzzlehttp/guzzle
    
  2. Start the server (default port 8086):
    ./vendor/bin/phiremock
    
  3. Configure your Laravel app to point to Phiremock during testing/development:
    // config/services.php (local/acceptance env)
    'external_api' => env('EXTERNAL_API_URL', 'http://localhost:8086'),
    

First Use Case: Mocking a Simple API Endpoint

  1. Define an expectation (via HTTP request or phiremock-client):
    curl -X POST http://localhost:8086/__phiremock/expectations \
      -H "Content-Type: application/json" \
      -d '{
        "version": "2",
        "on": {
          "method": {"isSameString": "GET"},
          "url": {"isEqualTo": "/api/users/1"}
        },
        "then": {
          "response": {
            "statusCode": 200,
            "body": "{\"id\":1,\"name\":\"John\"}",
            "headers": {"Content-Type": "application/json"}
          }
        }
      }'
    
  2. Test locally by calling http://localhost:8086/api/users/1—your app will receive the mocked response.

Implementation Patterns

1. Environment-Specific Configuration

Use Laravel's environment files to toggle between real and mocked services:

// .env.local
EXTERNAL_API_URL=http://localhost:8086

// .env.acceptance
EXTERNAL_API_URL=http://localhost:8086

2. Dynamic Expectations in Tests

Leverage phiremock-client in PHPUnit tests:

use Mcustiel\Phiremock\Client\Client;

public function testUserFetch()
{
    $client = new Client('http://localhost:8086');
    $client->addExpectation([
        'on' => ['method' => 'GET', 'url' => '/api/users/1'],
        'then' => ['response' => ['statusCode' => 200, 'body' => '{"id":1}']]
    ]);

    $response = Http::get('/api/users/1');
    $this->assertEquals(200, $response->status());
}

3. Scenario-Based Mocking

Simulate stateful APIs (e.g., OAuth flows):

// First request (sets state)
$client->addExpectation([
    'scenarioName' => 'auth_flow',
    'on' => ['scenarioStateIs' => 'START', 'method' => 'POST', 'url' => '/login'],
    'then' => [
        'newScenarioState' => 'AUTHORIZED',
        'response' => ['statusCode' => 200, 'body' => '{"token":"abc123"}']
    ]
]);

// Subsequent request (uses state)
$client->addExpectation([
    'scenarioName' => 'auth_flow',
    'on' => ['scenarioStateIs' => 'AUTHORIZED', 'method' => 'GET', 'url' => '/protected'],
    'then' => ['response' => ['statusCode' => 200, 'body' => '{"data":"secret"}']]
]);

4. Static Expectations for Development

Store expectations in ~/.phiremock/expectations/ (e.g., users.json):

{
  "version": "2",
  "on": {"method": "GET", "url": {"matches": "~^/api/users/~"}},
  "then": {"response": {"statusCode": 200, "body": "phiremock.base64:..."}}
}

Start Phiremock with:

./vendor/bin/phiremock --expectations-dir ~/.phiremock/expectations

5. Integration with Laravel HTTP Client

Use Laravel’s Http facade with Phiremock:

$response = Http::withOptions(['verify' => false])->get('http://localhost:8086/api/data');

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Headers/URLs: Phiremock matches headers/URLs case-sensitively by default. Use isEqualToIgnoringCase for flexibility.

    "headers": {"Accept": {"isEqualToIgnoringCase": "application/json"}}
    
  2. Base64 Encoding for Binary Data: Forgetting phiremock.base64: prefix will return raw base64 strings instead of decoded binary.

    "body": "phiremock.base64:SGVsbG8gV29ybGQ="  // Correct (decodes to "Hello World")
    
  3. Priority Conflicts: Unintended priority overlaps can cause flaky tests. Explicitly set priorities for critical paths:

    "priority": 100  // Highest priority
    
  4. Debugging Stuck Requests: Enable debug mode to log unmatched requests:

    ./vendor/bin/phiremock --debug
    

Debugging Tips

  • List All Expectations:
    curl http://localhost:8086/__phiremock/expectations
    
  • Verify Request Counts:
    curl -X POST http://localhost:8086/__phiremock/executions \
      -d '{"request": {"method": "GET", "url": {"isEqualTo": "/api/users"}}}'
    
  • Reset State:
    curl -X POST http://localhost:8086/__phiremock/reset
    

Extension Points

  1. Custom HTTP Client: Override the factory class to use Guzzle v7 or Symfony’s HttpClient:

    // app/Providers/PhiremockServiceProvider.php
    public function register()
    {
        $this->app->bind(
            \Mcustiel\Phiremock\Client\Factory::class,
            \App\Phiremock\Guzzle7Factory::class
        );
    }
    
  2. Dynamic Expectations from Database: Load expectations from Laravel’s database in a service provider:

    public function boot()
    {
        $client = new Client('http://localhost:8086');
        foreach (DB::table('mock_expectations')->get() as $expectation) {
            $client->addExpectation(json_decode($expectation->json, true));
        }
    }
    
  3. Codeception Integration: Use the phiremock-codeception-extension for test-specific mocks:

    # codeception.yml
    extensions:
        enabled:
            - Phiremock
    

Performance Quirks

  • Latency Simulation: Add artificial delay to simulate slow APIs:
    "then": {"delayMillis": 1500, "response": {...}}
    
  • Memory Usage: Clear expectations after tests to avoid leaks:
    $client->reset();
    

Security Notes

  • HTTPS Support: Use --certificate and --certificate-key for secure testing:
    ./vendor/bin/phiremock --certificate cert.pem --certificate-key key.pem
    
  • Avoid Hardcoding Secrets: Store certificates outside the project root (e.g., ~/.phiremock/certs/).
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky