PHP code example of themattosdev / leakless

1. Go to this page and download the library: Download themattosdev/leakless 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/ */

    

themattosdev / leakless example snippets


use TheMattos\Leakless\DTOs\Config;
use TheMattos\Leakless\Integrations\FrankenPhp\FrankenPhp;

FrankenPHP::run(
    app: function () {
        echo json_encode(['status' => 'ok']);
    },
    config: new Config(
        maxDriftMb: 64,
        maxRequests: 1000,
        resettables: [
            App\Services\CartSession::class,
            fn () => LegacyRegistry::$cache = [],
        ],
    ),
);

'resettables' => [
    App\Services\CartSession::class,
    fn () => LegacyRegistry::$cache = [],
],

use TheMattos\Leakless\Attributes\ResetOnRequest;

class UserContext
{
    // Static properties are reset when registering UserContext::class in 'resettables'
    #[ResetOnRequest]
    public static ?string $token = null;

    #[ResetOnRequest(default: 'guest')]
    public static string $role = 'guest';

    // Instance properties are reset when registering the object instance itself
    #[ResetOnRequest(default: [])]
    public array $permissions = [];
}

// In config/leakless.php:
'resettables' => [
    // Resets static #[ResetOnRequest] properties and static cleanup methods:
    UserContext::class,

    // To reset instance properties, register the resolved object instance or callback:
    // fn () => app(UserContext::class)->permissions = [],
],

test('service executes cleanly without leaking memory or state', function () {
    // 1. Structural design check (no mutable static props or illegal constructor injections)
    expect(PaymentService::class)->toBeLeakless();

    // 2. Full request lifecycle check (PDO transactions, FDs, and Linux RSS drift)
    expect(function () {
        (new PaymentService())->processPendingTransactions();
    })->toRunCleanly(maxDriftMb: 0.25);

    // 3. Deep container/instance property snapshotting (detects runtime state mutations)
    expect(app())->toResetContainerState(function () {
        $this->postJson('/api/checkout', ['item' => 'pro']);
    });
});