PHP code example of kdesilva / audit-trail

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

    

kdesilva / audit-trail example snippets


'AuditStash' => [
    'persister' => 'AuditStash\Persister\TablePersister'
]

$this->addBehavior('AuditStash.AuditLog');
$this->behaviors()->get('AuditLog')->persister()->config([
    'extractMetaFields' => [
        'user.name' => 'username'
    ]
]);

...
'AuditStash' => [
    'persister' => 'AuditStash\Persister\TablePersister',
    'extractMetaFields' => [
            'user.username' => 'username',
            'user.customer_id' => 'customer_id',
        ],
    'blacklist' => ['customer_id'],
],

class ArticlesTable extends Table
{
    public function initialize(array $config = [])
    {
        $this->setDisplayField('article_name');
        ...
        $this->addBehavior('AuditStash.AuditLog');
    }
}

class ArticlesTable extends Table
{
    public function initialize(array $config = [])
    {
        $this->setDisplayField('article_name');
        ...
        $this->addBehavior('AuditStash.AuditLog', [
            'blacklist' => ['created', 'modified', 'another_field_name']
        ]);
    }
}

class ArticlesTable extends Table
{
    public function initialize(array $config = [])
    {
        $this->setDisplayField('article_name');
        ...
        $this->addBehavior('AuditStash.AuditLog', [
            'whitelist' => ['title', 'description', 'author_id']
        ]);
    }
}


public function initialize(array $config = [])
{
    $this->setDisplayField('article_name');
    ...
    $this->addBehavior('AuditStash.AuditLog', [
        'blacklist' => ['customer_id', 'product_id'],
        'foreignKeys' => [
            'Categories' => 'name', // foreign key Model => human-friendly field name
            'ProductStatuses' => 'status',
        ],
        'unsetAssociatedEntityFieldsNotDirtyByFieldName' => [
            'associated_table_name' => 'field_name_in_associated_table'
        ]
    ]);
}

use AuditStash\Meta\RequestMetadata;
...

class AppController extends Controller
{
    public function beforeFilter(Event $event)
    {
        ...
        $eventManager = $this->loadModel()->eventManager();
        $identity = $this->request->getAttribute('identity');
        if ($identity != null) {
            $eventManager->on(
                 new RequestMetadata($this->request, [
                    'username' => $identity['username'],
                    'customer_id' => $identity['customer_id'],
                ])
            );
        }
    }
}

use AuditStash\Meta\RequestMetadata;
use Cake\Event\EventManager;
...

class AppController extends Controller
{
    public function beforeFilter(Event $event)
    {
        ...
        $identity = $this->request->getAttribute('identity');
        if ($identity != null) {
            EventManager::instance()->on(
                new RequestMetadata($this->request, [
                    'username' => $identity['username'],
                    'customer_id' => $identity['customer_id'],
                ])
            );
        }
    }
}

use AuditStash\Meta\ApplicationMetadata;
use Cake\Event\EventManager;

EventManager::instance()->on(new ApplicationMetadata('my_blog_app', [
    'server' => $theServerID,
    'extra' => $somExtraInformation,
    'moon_phase' => $currentMoonPhase
]));


EventManager::instance()->on('AuditStash.beforeLog', function ($event, array $logs) {
    foreach ($logs as $log) {
        $log->setMetaInfo($log->getMetaInfo() + ['extra' => 'This is extra data to be stored']);
    }
});

use AuditStash\PersisterInterface;

class MyPersister implements PersisterInterface
{
    public function logEvents(array $auditLogs)
    {
        foreach ($auditLogs as $log) {
            $eventType = $log->getEventType();
            $data = [
                'timestamp' => $log->getTimestamp(),
                'transaction' => $log->getTransactionId(),
                'type' => $log->getEventType(),
                'primary_key' => $log->getId(),
                'display_value' => $event->getDisplayValue(),
                'source' => $log->getSourceName(),
                'parent_source' => $log->getParentSourceName(),
                'original' => json_encode($log->getOriginal()),
                'changed' => $eventType === 'delete' ? null : json_encode($log->getChanged()),
                'meta' => json_encode($log->getMetaInfo())
            ];
            $storage = new MyStorage();
            $storage->save($data);
        }
    }
}

'AuditStash' => [
    'persister' => 'App\Namespace\For\Your\Persister'
]

\Cake\Core\Configure::write('AuditStash.persister', 'App\Namespace\For\Your\DatabasePersister');


namespace App\Model\Audit;

use Cake\Utility\Text;
use SplObjectStorage;

class AuditTrail
{
    protected $_auditQueue;
    protected $_auditTransaction;

    public function __construct()
    {
        $this->_auditQueue = new SplObjectStorage;
        $this->_auditTransaction = Text::uuid();
    }

    public function toSaveOptions()
    {
        return [
            '_auditQueue' => $this->_auditQueue,
            '_auditTransaction' => $this->_auditTransaction
        ];
    }
}

use App\Model\Audit\AuditTrail;
use Cake\Event\Event;

$trail = new AuditTrail();
$success = $this->Bookmarks->connection()->transactional(function () use ($trail) {
    $bookmark = $this->Bookmarks->newEntity();
    $bookmark1->save($data1, $trail->toSaveOptions());
    $bookmark2 = $this->Bookmarks->newEntity();
    $bookmark2->save($data2, $trail->toSaveOptions());
    ...
    $bookmarkN = $this->Bookmarks->newEntity();
    $bookmarkN->save($dataN, $trail->toSaveOptions());

    return true;
});

if ($success) {
    $event = new Event('Model.afterCommit', $this->Bookmarks);
    $table->behaviors()->get('AuditLog')->afterCommit($event, $result, $auditTrail->toSaveOptions());
}

...
$auditTrail = new AuditTrail();

if ($this->Bookmarks->saveMany($entities, $auditTrail->toSaveOptions())) {
    ...                   
}