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 Common Laravel Package

mcustiel/phiremock-common

Shared utilities for the Phiremock PHP ecosystem. Provides common classes, interfaces, and helpers used across related packages to simplify building and consuming Phiremock client/server components with consistent behavior and minimal duplication.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mcustiel/phiremock-common
    

    Updated Requirement: Ensure your project uses PHP 8.2+ and Laravel 9+ (verify via composer.json constraints). PHP 8.1 and below are no longer supported.

  2. First Use Case: Mocking HTTP Responses Import the core trait and use it in a test:

    use Mcustiel\PhiremockCommon\Traits\MockHttpResponse;
    
    class MyTest extends TestCase
    {
        use MockHttpResponse;
    
        public function test_mocked_response()
        {
            $this->mockHttpResponse('GET', 'https://api.example.com/data', 200, ['key' => 'value']);
            $response = Http::get('https://api.example.com/data');
            $this->assertEquals(['key' => 'value'], $response->json());
        }
    }
    
  3. Key Classes to Explore

    • MockHttpResponse trait: For HTTP mocking.
    • MockDatabase trait: For database query mocking.
    • PhiremockServiceProvider: Registers package services (if applicable).

Implementation Patterns

HTTP Mocking Workflow

  1. Define Mocks in Tests

    $this->mockHttpResponse(
        method: 'POST',
        url: 'https://api.example.com/webhooks',
        status: 201,
        headers: ['X-Webhook-ID' => '123'],
        body: json_encode(['success' => true])
    );
    
  2. Conditional Mocking Use closures for dynamic responses (PHP 8.2+ features like named arguments and attributes are fully supported):

    $this->mockHttpResponse('GET', 'https://api.example.com/user/{id}', function ($request) {
        return response()->json(['id' => $request->id, 'name' => 'Test User']);
    });
    
  3. Integration with Laravel HTTP Client Works seamlessly with Http::macro() or Http::as():

    $this->mockHttpResponse('GET', 'https://api.example.com/data', 200, ['data' => []]);
    $response = Http::withOptions(['debug' => false])->get('https://api.example.com/data');
    

Database Mocking Workflow

  1. Mock Eloquent Queries

    use Mcustiel\PhiremockCommon\Traits\MockDatabase;
    
    $this->mockDatabaseQuery(
        User::query()->where('active', true),
        ['id' => 1, 'name' => 'Admin']
    );
    
  2. Stub Database Connections Override connections for specific tests:

    $this->mockDatabaseConnection('mysql', function ($query) {
        return collect([['id' => 1, 'name' => 'Mock User']]);
    });
    

Common Patterns

  • Test Isolation: Reset mocks between tests using:
    $this->resetMocks();
    
  • Global Mocks: Set up mocks in setUp() for reusable test suites.
  • Assertions: Combine with Laravel’s assertDatabaseHas() or custom assertions:
    $this->assertMockWasCalled('GET', 'https://api.example.com/data');
    

Gotchas and Tips

Pitfalls

  1. URL Matching Strictness

    • Mocks use exact URL matching by default. Use regex patterns for flexibility:
      $this->mockHttpResponse('GET', '/api/users/.*', 200, []);
      
    • Fix: Escape special characters in URLs (e.g., https:\/\/api\.example\.com).
  2. Case Sensitivity

    • HTTP methods (GET, Post) are case-insensitive, but headers/URLs may not be. Normalize inputs:
      $this->mockHttpResponse(strtoupper('get'), 'https://api.example.com/data', ...);
      
  3. Database Mocking Scope

    • Mocks only affect the current test. Avoid leaking mocks into other tests.
    • Tip: Use afterApplicationCreated() in TestCase to reset mocks globally.
  4. PHP 8.2+ Breaking Changes

    • Deprecated: PHP 8.1 and below are no longer supported. Update your project or use a compatible version of the package.
    • New Features: PHP 8.2+ features like readonly properties and new attributes may be leveraged in future updates.
  5. Performance Overhead

    • Mocking every HTTP call in a test suite can slow down execution. Use sparingly for critical paths.

Debugging Tips

  1. Verify Mocks

    $this->assertMockExists('GET', 'https://api.example.com/data');
    $this->assertMockWasCalled('GET', 'https://api.example.com/data');
    
  2. Inspect Requests Use closures to log requests:

    $this->mockHttpResponse('GET', 'https://api.example.com/data', function ($request) {
        \Log::debug('Mocked request:', $request->toArray());
        return response()->json(['data' => []]);
    });
    
  3. Clear Mocks Explicitly If tests fail due to stale mocks, force a reset:

    $this->resetMocks(); // Clear all HTTP/database mocks
    

Extension Points

  1. Custom Matchers Extend the trait to add custom logic:

    protected function shouldMockRequest($method, $url, $request)
    {
        return $request->hasHeader('X-Custom-Header');
    }
    
  2. Mocking Exceptions Simulate API errors:

    $this->mockHttpResponse('GET', 'https://api.example.com/fail', 500, [], 'Internal Server Error');
    
  3. Integration with Pest Works with Pest via traits or mixins:

    uses(MockHttpResponse::class)->in('Feature');
    

Configuration Quirks

  • No Config File: The package relies on runtime configuration via method arguments.
  • Priority: Later mocks override earlier ones. Order matters in test setup.
  • Thread Safety: Mocks are test-isolated but not thread-safe across parallel tests. Use refreshTestingTask() in CI.
  • PHP 8.2+ Optimizations: Future releases may introduce optimizations leveraging PHP 8.2+ features like enums or new error handling.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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