PHP code example of vildanbina / hookshot

1. Go to this page and download the library: Download vildanbina/hookshot library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vildanbina / hookshot example snippets


Route::middleware('track-requests')->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
    Route::post('/api/users', [UserController::class, 'store']);
});

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\VildanBina\HookShot\Middleware\TrackRequestsMiddleware::class);
})

use VildanBina\HookShot\Facades\RequestTracker;

// Get all recent requests
$requests = RequestTracker::get(50);

// Find specific request by ID
$request = RequestTracker::find('uuid-here');

// Get requests with database driver (supports advanced queries)
$slowRequests = RequestTracker::query()
    ->where('execution_time', '>', 2.0)
    ->where('response_status', '>=', 400)
    ->get();

// Filter by date range
$todayRequests = RequestTracker::query()
    ->whereDate('timestamp', today())
    ->get();

use VildanBina\HookShot\Events\RequestCaptured;
use Illuminate\Support\Facades\Event;

Event::listen(RequestCaptured::class, function (RequestCaptured $event) {
    $request = $event->request;
    $requestData = $event->requestData;
    
    // Do something with the request and request data
});



declare(strict_types=1);

return [
    /*
    |--------------------------------------------------------------------------
    | HookShot Request Tracking
    |--------------------------------------------------------------------------
    |
    | This file contains the configuration options for HookShot request tracking.
    | You can enable/disable tracking, choose storage drivers, and configure
    | filtering options to control what gets tracked.
    |
    */

    // Enable or disable request tracking globally
    'enabled' => env('HOOKSHOT_ENABLED', true),

    // Default storage driver: 'database', 'cache', or 'file'
    'default' => env('HOOKSHOT_DRIVER', 'database'),

    /*
    |--------------------------------------------------------------------------
    | Storage Drivers
    |--------------------------------------------------------------------------
    |
    | Configure how and where request data is stored. Each driver has its own
    | settings for connection, retention, and other storage-specific options.
    |
    */
    'drivers' => [
        'database' => [
            'connection' => env('HOOKSHOT_DB_CONNECTION'),
            'table' => env('HOOKSHOT_TABLE', 'hookshot_logs'),
            'retention_days' => 30,
        ],

        'cache' => [
            'store' => env('HOOKSHOT_CACHE_STORE'),
            'prefix' => 'hookshot',
            'retention_days' => 7,
            'max_index_size' => 10000,
        ],

        'file' => [
            'path' => storage_path('app/hookshot'),
            'format' => 'json', // json or raw
            'retention_days' => 30,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Exclusion Filters
    |--------------------------------------------------------------------------
    |
    | Define which requests should be excluded from tracking to reduce noise
    | and focus on meaningful application requests.
    |
    */

    // Paths to exclude from tracking (health checks, admin panels, etc.)
    'excluded_paths' => [
        'health-check',
        'up',
        '_debugbar/*',
        'telescope/*',
        'horizon/*',
        'pulse/*',
    ],

    // User agents to exclude (monitoring tools, bots, crawlers)
    'excluded_user_agents' => [
        'pingdom',
        'uptimerobot',
        'googlebot',
        'bingbot',
    ],

    /*
    |--------------------------------------------------------------------------
    | Performance Controls
    |--------------------------------------------------------------------------
    |
    | Configure performance-related settings to manage resource usage and
    | ensure tracking doesn't impact application performance.
    |
    */

    // Percentage of requests to track (1.0 = 100%, 0.5 = 50%, etc.)
    'sampling_rate' => env('HOOKSHOT_SAMPLING_RATE', 1.0),

    // Maximum size of request payload to store (in bytes)
    'max_payload_size' => 65536, // 64KB

    // Maximum size of response body to store (in bytes)
    'max_response_size' => 10240, // 10KB

    // Queue request tracking for better performance
    'use_queue' => env('HOOKSHOT_USE_QUEUE', false),

    /*
    |--------------------------------------------------------------------------
    | Security Settings
    |--------------------------------------------------------------------------
    |
    | Configure security-related settings for request tracking to ensure
    | sensitive data is properly filtered and protected.
    |
    */

    // Headers to filter/redact in request and response tracking
    'sensitive_headers' => [
        'authorization',
        'cookie',
        'set-cookie',
        'x-api-key',
        'x-auth-token',
        'x-csrf-token',
        'x-xsrf-token',
    ],

    /*
    |--------------------------------------------------------------------------
    | Response Capture Settings
    |--------------------------------------------------------------------------
    |
    | Configure which responses should be captured and stored for analysis.
    | These settings help control what response data is worth storing.
    |
    */

    // Enable or disable response header capture (saves database space)
    'capture_response_headers' => env('HOOKSHOT_CAPTURE_RESPONSE_HEADERS', true),

    // Enable or disable response body capture (saves significant database space)
    'capture_response_body' => env('HOOKSHOT_CAPTURE_RESPONSE_BODY', true),

    // Content types to exclude from response body capture (prefix matching)
    'excluded_content_types' => [
        'image/',
        'video/',
        'audio/',
        'application/pdf',
        'application/zip',
        'application/octet-stream',
    ],

    // HTTP status codes that are considered important to capture
    'important_status_codes' => [
        200,  // OK
        201,  // Created  
        400,  // Bad Request
        401,  // Unauthorized
        403,  // Forbidden
        404,  // Not Found
        422,  // Unprocessable Entity
        500,  // Internal Server Error
    ], 
];



namespace App\HookShot\Drivers;

use Illuminate\Support\Collection;
use VildanBina\HookShot\Contracts\StorageDriverContract;
use VildanBina\HookShot\Data\RequestData;

class CustomApiDriver implements StorageDriverContract
{
    public function __construct(array $config = [])
    {
        // Initialize your driver with config (API keys, endpoints, etc.)
    }

    public function store(RequestData $requestData): bool
    {
        // Store the request data to your storage system
        // Return true on success, false on failure
    }

    public function find(string $id): ?RequestData
    {
        // Find and return a specific request by ID
        // Return null if not found
    }

    public function get(int $limit = 100): Collection
    {
        // Get multiple requests with the given limit
        // Return Collection of RequestData objects
    }

    public function delete(string $id): bool
    {
        // Delete a specific request by ID
        // Return true if deleted, false otherwise
    }

    public function cleanup(): int
    {
        // Clean up old requests based on retention policy
        // Return number of deleted requests
    }

    public function isAvailable(): bool
    {
        // Check if your storage system is available
        // Return true if operational, false otherwise
    }
}

// config/hookshot.php
'default' => 'custom',

'drivers' => [
    // other drivers
    
    'custom' => [
        'via' => \App\HookShot\Drivers\CustomApiDriver::class,
        'endpoint' => env('CUSTOM_ENDPOINT', 'https://api.example.com'),
        'api_key' => env('CUSTOM_KEY'),
    ],
],

[
    'id' => 'uuid',
    'method' => 'POST',
    'url' => 'https://app.com/api/users',
    'path' => 'api/users',
    'headers' => ['accept' => ['application/json']],
    'payload' => ['name' => 'John', 'email' => '[email protected]'],
    'ip' => '192.168.1.1',
    'user_agent' => 'Mozilla/5.0...',
    'user_id' => 123,
    'timestamp' => '2024-01-15T10:30:00Z',
    'execution_time' => 0.250,
    'response_status' => 201,
    'response_body' => ['id' => 456, 'name' => 'John'],
]
bash
php artisan vendor:publish --tag=hookshot-config
bash
php artisan migrate