PHP code example of padosoft / laravel-ai-act-compliance

1. Go to this page and download the library: Download padosoft/laravel-ai-act-compliance 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/ */

    

padosoft / laravel-ai-act-compliance example snippets


class MyAppExporter implements \Padosoft\AiActCompliance\DSAR\Contracts\UserDataExporter
{
    public function export(\App\Models\User $user): array {
        return [
            'profile' => $user->only(['id', 'name', 'email']),
            'orders' => $user->orders()->get()->toArray(),
            'chats' => $user->chats()->withTrashed()->get()->toArray(),
        ];
    }
}

class MyAppDeleter implements \Padosoft\AiActCompliance\DSAR\Contracts\UserDataDeleter
{
    public function delete(\App\Models\User $user, array $scope): void {
        $user->orders()->delete();
        $user->chats()->forceDelete();
        $user->delete();
    }
}

class RefusalRateMetric implements \Padosoft\AiActCompliance\BiasMonitoring\Contracts\CohortParityMetric
{
    public function compute(array $context = []): array {
        // Your domain logic: count refusals per cohort in $context['window_days']
        return [
            'cohort' => $context['cohort'],
            'score' => 1 - ($refusals / $total),
            'delta' => $baseline - (1 - $refusals / $total),
            'flagged' => /* delta > threshold */,
        ];
    }
}

// In your AppServiceProvider:
app('ai-act.bias')->register('refusal_rate', RefusalRateMetric::class);

$ticket = app('ai-act.incidents')->open([
    'title' => 'Hallucination on legal queries (IT cohort)',
    'severity' => IncidentSeverity::High,
    'affected_users' => $userIds,
    'articles' => ['AI Act Art. 14', 'AI Act Art. 15'],
]);

app('ai-act.incidents')->transition($ticket, IncidentStatus::Triage);
app('ai-act.incidents')->transition($ticket, IncidentStatus::Mitigating, [
    'mitigation' => 'Deployed v2.4.2 with extended IBAN regex.',
]);

// Default OFF. Enable + seed an alert_routes row + you're done.
config(['ai-act-compliance.alerting.enabled' => true]);

AlertRoute::query()->create([
    'tenant_id' => 'acme',
    'channel' => 'slack',
    'webhook_url' => 'https://hooks.slack.com/services/...',  // auto-encrypted at rest
    'enabled' => true,
]);

// Whenever BiasMonitorService::capture() ingests a drift snapshot
// above the configured threshold, the queued listener fans out:
//   Slack → Discord → ALWAYS email (audit trail)

Tenant::query()->create([
    'slug' => 'acme',                           // unique 50-char id
    'name' => 'Acme Inc.',
    'subscription_tier' => 'enterprise',
    'dpo_email' => '[email protected]',
    'config_overrides_json' => [
        // Per-tenant override of ANY ai-act-compliance.* key
        'bias.disparity_threshold' => 0.02,
    ],
]);

// Mount the middleware on whatever route group you serve to operators:
Route::middleware('ai-act.tenant-context')->group(function () {
    Route::get('/api/admin/ai-act-compliance/...', ...);
});

// Every package service reads the active tenant via:
$current = app(TenantContext::class)->current();
$threshold = app(TenantConfigResolver::class)->resolve('bias.disparity_threshold', 0.05);



namespace App\Compliance;

use App\Models\User;
use Padosoft\AiActCompliance\DSAR\Contracts\UserDataExporter;

class MyAppUserDataExporter implements UserDataExporter
{
    public function export(User $user): array
    {
        return [
            // List EVERY domain table that holds data for this user.
            // The package will ZIP this and ship to the DSAR delivery URL.
            'profile' => $user->only(['id', 'name', 'email', 'created_at']),
            'orders' => $user->orders()->get()->toArray(),
            'chats' => $user->chats()->get()->toArray(),
            // Add every relation you persist for users.
        ];
    }
}



namespace App\Compliance;

use App\Models\User;
use Padosoft\AiActCompliance\DSAR\Contracts\UserDataDeleter;

class MyAppUserDataDeleter implements UserDataDeleter
{
    public function delete(User $user, array $scope): void
    {
        // Cascade delete EVERY domain table. The package handles the
        // audit trail and the SLA tracking; you handle the actual rows.
        $user->orders()->delete();
        $user->chats()->forceDelete();
        $user->delete();
    }
}

public function register(): void
{
    $this->app->bind(
        \Padosoft\AiActCompliance\DSAR\Contracts\UserDataExporter::class,
        \App\Compliance\MyAppUserDataExporter::class,
    );
    $this->app->bind(
        \Padosoft\AiActCompliance\DSAR\Contracts\UserDataDeleter::class,
        \App\Compliance\MyAppUserDataDeleter::class,
    );
}

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'ai-act.disclosure' => \Padosoft\AiActCompliance\Disclosure\AiDisclosureMiddleware::class,
    ]);
})

Route::middleware('ai-act.disclosure')->group(function () {
    Route::post('/chat', [ChatController::class, 'send']);
});

return [
    'disclosure' => [
        'enabled' => env('AICOMPLIANCE_DISCLOSURE_ENABLED', true),
        'message' => env('AICOMPLIANCE_DISCLOSURE_MESSAGE', 'You are chatting with an AI assistant. Responses may be inaccurate.'),
    ],

    'dsar' => [
        'sla_days' => env('AICOMPLIANCE_DSAR_SLA_DAYS', 30),
        'warn_days' => env('AICOMPLIANCE_DSAR_WARN_DAYS', 5),
        'notify_emails' => array_filter(explode(',', env('AICOMPLIANCE_DSAR_NOTIFY', ''))),
    ],

    'bias' => [
        'enabled' => env('AICOMPLIANCE_BIAS_ENABLED', true),
        'baseline_parity' => env('AICOMPLIANCE_BIAS_BASELINE_PARITY', 0.95),
        'drift_threshold' => env('AICOMPLIANCE_BIAS_DRIFT_THRESHOLD', 0.05),
        'window_days' => env('AICOMPLIANCE_BIAS_WINDOW_DAYS', 7),
    ],

    'incidents' => [
        'escalation_map' => [
            'critical' => ['[email protected]', '[email protected]'],
            'high' => ['[email protected]'],
            'medium' => ['[email protected]'],
            'low' => [],
        ],
    ],

    'consent' => [
        'features' => [
            // Declare per-feature consent flags here.
        ],
    ],

    'cybersecurity' => [
        'rate_limit_per_user' => env('AICOMPLIANCE_RATE_LIMIT_PER_USER', '60,1'),
        'session_anomaly_strict' => env('AICOMPLIANCE_SESSION_ANOMALY_STRICT', false),
    ],

    'attestation' => [
        'signer' => env('AICOMPLIANCE_ATTESTATION_SIGNER', 'DPO <[email protected]>'),
    ],
];

interface UserDataExporter
{
    /**
     * Return a serializable array of ALL data the host stores for this user.
     * The package handles ZIP packaging, signed URL delivery, audit trail.
     */
    public function export(\Illuminate\Foundation\Auth\User $user): array;
}

interface UserDataDeleter
{
    /**
     * Cascade-delete EVERY row referencing this user across the host's
     * domain. The package handles the DSAR queue state transition + audit.
     *
     * @param array<string, mixed> $scope Optional scope from the DSAR
     *   request payload (e.g. {"keep_invoices": true}).
     */
    public function delete(\Illuminate\Foundation\Auth\User $user, array $scope = []): void;
}
bash
# Schedule it daily — defaults OFF; opt in via AI_ACT_REGULATORY_FEED_ENABLED=true.
php artisan ai-act:regulatory-poll
bash
php artisan vendor:publish --tag=ai-act-compliance-migrations
php artisan vendor:publish --tag=ai-act-compliance-config
bash
php artisan migrate
bash
php artisan tinker
>>> \Padosoft\AiActCompliance\DSAR\Models\DsarRequest::query()->count();
=> 0
>>> exit
bash
php artisan tinker
>>> $request = \Padosoft\AiActCompliance\DSAR\Models\DsarRequest::create([
...     'subject_email' => '[email protected]',
...     'type' => 'export',
...     'status' => 'pending',
... ]);
>>> $request->id;
=> 1
>>> exit