metalogico/laravel-mocka

Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic

1.0.2 2025-08-25 17:07 UTC

This package is auto-updated.

Last update: 2025-08-25 18:15:46 UTC


README

Latest Version on Packagist

Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic.

Why Mocka?

When your Laravel app calls external APIs (like DMS, MES, or any third-party service), you often need to provide mock responses for:

  • ๐ŸŽ App Store Reviews - Apple and Google reviewers need working apps without real API access
  • ๐Ÿงช Testing Environments - Stable, predictable responses for your test suite
  • ๐Ÿ‘ฅ Demo Users - Showcase your app without depending on external services
  • ๐Ÿš€ Development - Work offline or with unstable external APIs

Features

  • ๐ŸŽฏ User-specific mocking - Mock responses only for designated users
  • ๐Ÿ”„ Drop-in replacement - Use MockaHttp instead of Laravel's Http facade
  • ๐Ÿ“ File-based mocks - Organize mock responses in PHP files
  • ๐ŸŽจ Response templating - Dynamic mock responses with Faker integration
  • ๐Ÿ“Š Request logging - Track which requests are mocked vs real
  • โŒ Error simulation - Test failure scenarios easily
  • ๐Ÿ›ฃ๏ธ Header activator - Enable/disable mocking via X-Mocka header
  • ๐Ÿ“ Force activation - Enable/disable mocking via withOptions(['mocka' => true])
  • ๐ŸŒ Rate limiting simulation - Simulate slow APIs delays for testing
  • ๐Ÿ” Advanced URL matching - Regex, wildcards, and parameter matching (coming soon โ„ข)
  • โŒ˜ Command Line tools - List mappings
  • โšก Zero performance impact - Only active for designated users

Installation

You can install the package via composer:

composer require metalogico/laravel-mocka

Publish the config file:

php artisan vendor:publish --tag="mocka-config"

Quick Start

1. Configure Mock Users

In your .env file:

MOCKA_ENABLED=true
MOCKA_USERS=reviewer@apple.com,tester@google.com,demo@yourapp.com
MOCKA_LOGS=true

2. Create Mock Files

Create mock files in resources/mocka/:

resources/mocka/api.mock.php

<?php

return [
    'POST' => [
        'authenticate' => [
            'success' => true,
            'user_id' => 12345,
            'token' => 'mock_token_12345',
            'expires_at' => time() + 3600,
        ],
    ],
    'GET' => [
        'getFileList' => [
            'success' => true,
            'files' => [
                [
                    'name' => 'file1.pdf',
                    'size' => 1024,
                    'created_at' => '2023-01-01 00:00:00',
                ],
                [
                    'name' => 'file2.pdf',
                    'size' => 2048,
                    'created_at' => '2023-01-02 00:00:00',
                ],
                // ...
            ],
        ]
    ],
];

3. Configure URL Mappings

In config/mocka.php:

'mappings' => [
    [
        'url' => env('EXTERNAL_API_URL').'/api/authenticate',
        'file' => 'api.mock.php',
        'key' => 'POST.authenticate',
    ],
    [
        'url' => env('EXTERNAL_API_URL').'/api/files/',
        'file' => 'api.mock.php',
        'key' => 'GET.getFileList',
    ],
];

4. Use MockaHttp in Your Services

Replace Laravel's Http facade with MockaHttp:

<?php

namespace App\Services;

use Metalogico\Mocka\Facades\MockaHttp;

class DmsService
{
    public static function authenticate($user, $password)
    {
        $response = MockaHttp::post(config('external_api_url').'/api/authenticate', [
            'user' => $user,
            'password' => $password,
        ]);

        session()->put('token', $response->json()['token']);

        return $response->json();
    }

    public static function getFileList()
    {
        $response = MockaHttp::withHeaders([
            'Authorization' => 'Bearer '.session()->get('token'),
        ])->get(config('external_api_url').'/api/files');

        return $response->json();
    }
}

Advanced Features

Response Types: Static, Dynamic, or Hybrid

Mocka supports three approaches for mock responses:

Static Responses

Perfect for app store reviews and basic demos:

return [
    'GET' => [
        'simpleAuth' => [
            'success' => true,
            'token' => 'static_token_123',
            'user_id' => 12345,
        ],
    ],
];

Dynamic Responses

For complex testing with varying data:

return [
    'GET' => [
        'userList' => fn() => [
            'users' => collect(range(1, fake()->numberBetween(3, 8)))
                ->map(fn() => [
                    'name' => fake()->name,
                    'email' => fake()->email,
                ]),
            'total' => fake()->numberBetween(50, 200),
            ],
        ],
    ],
];

Hybrid Responses

You can even mix static and dynamic data as needed:

return [
    'GET' => [
        'mixedResponse' => fn() => [
            'status' => 'success',        // Static
            'timestamp' => time(),        // Static but with function
            'dynamic_data' => fn() => [
                'user_count' => fake()->numberBetween(5, 20),
                'featured_products' => collect(range(1, 3))
                    ->map(fn() => [
                        'id' => fake()->numberBetween(1000, 9999),
                        'name' => fake()->words(3, true),
                        'price' => fake()->randomFloat(2, 10, 500),
                    ]),
                ],
            ],
        ],
    ],
];

Advanced URL Matching

Configure sophisticated URL matching patterns:

'mappings' => [
    // Exact match
    [
        'url' => 'https://api.example.com/users/123',
        'match' => 'exact', // which is the default
        'file' => 'users.mock.php',
        'key' => 'GET.specificUser',
    ],
    
    // Wildcard matching
    [
        'url' => 'https://api.example.com/users/*',
        'match' => 'wildcard',
        'file' => 'users.mock.php',
        'key' => 'GET.anyUser',
    ],
    
    // Regex matching (coming soom โ„ข)
    [
        'url' => '/^https:\/\/api\.example\.com\/orders\/\d+$/',
        'match' => 'regex',
        'file' => 'orders.mock.php',
        'key' => 'GET.orderDetail',
    ],
];

Error Simulation

Simulate API errors by defining error configurations in your mappings:

'mappings' => [
    [
        'url' => 'https://api.example.com/users/123',
        'file' => 'users.mock.php',
        'key' => 'GET.specificUser',
        'errors' => 'GET.specificUserErrors' // Optional error configuration
    ],
];

Define error responses in your mock files:

return [
    'GET' => [
        'specificUser' => fn() => [
            'id' => fake()->numberBetween(1000, 9999),
            'name' => fake()->name,
            'email' => fake()->email,
        ],
        
        'specificUserErrors' => [
            'error_rate' => 25, // 25% chance of error
            'errors' => [
                422 => [
                    'message' => 'Validation failed',
                    'errors' => ['name' => ['Name is required']]
                ],
                404 => [
                    'message' => 'User not found',
                    'code' => 'USER_NOT_FOUND',
                    'timestamp' => time()
                ],
                503 => fn() => [ // Dynamic error responses
                    'message' => 'Service temporarily unavailable',
                    'retry_after' => fake()->numberBetween(30, 300),
                    'incident_id' => fake()->uuid,
                ],
            ],
        ],
    ],
];

Rate Limiting Simulation

Add delays to simulate slow APIs:

'mappings' => [
    [
        'url' => 'https://slow-api.com/data',
        'file' => 'slow.mock.php',
        'key' => 'GET.slowResponse',
        'delay' => 5000, // 5 second delay
    ],
];

Jobs and Artisan (Force Activation)

When running inside queued Jobs or Artisan commands (where there is no web request/user), you can explicitly enable Mocka per request using options:

use Metalogico\Mocka\Facades\MockaHttp;

$enabled = ($user === 'reviewer@apple.com') ? true : false; 

$response = MockaHttp::withOptions(['mocka' => $enabled])
    ->get(config('external_api_url').'/api/files');

Notes:

  • Mocka must still be enabled and allowed in the current environment/host by config.
  • If the current user is in MOCKA_USERS, forcing is not required (it's always active).
  • You can also use the X-Mocka header in regular request contexts to activate per-call.

Artisan Commands

List Mock Mappings

List all configured mappings and whether they correctly resolve to a mock file/key. The output uses a compact, two-line layout per mapping:

php artisan mocka:list

Per mapping you will see two rows:

  • Main row โ€” shows mapping details and overall Status for file/key resolution.
  • Sub-row โ€” shows the errors key (or - if none) in the key column, and its validation result in status.

Configuration

The configuration file config/mocka.php supports these options:

return [
    // Globally enable Mocka (default: false in production)
    'enabled' => env('MOCKA_ENABLED', false),

    // Enable request logging (default: true in development)
    'logs' => env('MOCKA_LOGS', true),

    // Users that get mocked responses
    'users' => array_filter(explode(',', env('MOCKA_USERS', ''))),

    // Path to mock files
    'mocks_path' => resource_path('mocka'),

    // Default delay for all mocked requests (milliseconds)
    'default_delay' => 0,

    // Security: only allow mocking for these hostnames (empty => all hosts allowed)
    'allowed_hosts' => [],

    // Allowed application environments for Mocka activation (default: local only)
    // Extend this to enable in other envs, e.g. ['local', 'staging']
    'environments' => ['local'],

    // URL mappings
    'mappings' => [
        // Your API mappings here
    ],
];
  • allowed_hosts: restricts Mocka activation to specific upstream hosts; leave empty to allow all.
  • environments: restricts activation to these Laravel environments (default ['local']).

How It Works

  1. Activation Check: If enabled and allowed by environment/host, Mocka checks activation triggers in order: user allowlist, withOptions(['mocka' => true]), or X-Mocka header
  2. URL Matching: If the user should be mocked, it matches the request URL against the configured mappings
  3. Mock Loading: Loads the appropriate mock file and extracts the response using dot notation
  4. Template Processing: Processes any template variables (faker, time functions, etc.)
  5. Response Simulation: Returns the mock response with optional delays or errors
  6. Logging: Logs whether the request was mocked or passed through

Testing

composer test

Security

If you discover any security related issues, please email metalogico@gmail.com instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.

Made with โ˜• in Italy