PHP code example of glesys / butler-audit

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

    

glesys / butler-audit example snippets


audit($user)->subscribed(['months' => 12]);

Auditor::initiatorResolver(fn () => [
    auth()->id(),
    [
        'ip' => request()->ip(),
        'userAgent' => request()->userAgent(),
    ]
]);

class Car extends Fluent implements Auditable
{
    public function auditorType(): string
    {
        return $this->type;
    }

    public function auditorIdentifier()
    {
        return $this->id;
    }
}

$car = new Car(['id' => 1, 'type' => 'volvo']);

audit($car)->started(); // equivalent to audit(['volvo', 1])->started();

class User extends Model implements Auditable
{
    use IsAuditable;
}

$user = User::find(1);

audit($user)->subscribed(); // equivalent to audit(['user', 1])->subscribed();

// Service A
audit($user)->signedUp();
Http::withCorrelation()->post('https://service-b.example/welcome-email', $user);

// Service B
audit($user)->welcomed();
Http::withCorrelation()->post('https://service-c.example/notify-staff');

// Service C
audit($employee)->notified();

public function test_welcome_user()
{
    Auditor::fake();

    // Assert that nothing was logged...
    Auditor::nothingLogged();

    // Perform user welcoming...

    // Assert 1 event was logged...
    Auditor::assertLoggedCount(1);

    // Assert a event was logged...
    Auditor::assertLogged('user.welcomed');

    // Assert a event with context, initiator and entity was logged...
    Auditor::assertLogged('user.welcomed', fn (AuditData $audit)
        => $audit->initiator === 'service-a'
        && $audit->hasEntity('user', 1)
        && $audit->hasEventContext('months', 12)
    );
}