PHP code example of mapik / audit-log

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

    

mapik / audit-log example snippets


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

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

...
'AuditLog' => [
    'persister' => 'AuditLog\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('AuditLog.AuditLog');
    }
}

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

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


public function initialize(array $config = [])
{
    $this->setDisplayField('article_name');
    ...
    $this->addBehavior('AuditLog.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 AuditLog\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 AuditLog\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 AuditLog\Meta\ApplicationMetadata;
use Cake\Event\EventManager;

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


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

use AuditLog\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);
        }
    }
}

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

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


namespace App\Model\Audit;

use Cake\Utility\Text;
use SplObjectStorage;

class AuditLog
{
    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\AuditLog;
use Cake\Event\Event;

$auditLog = new AuditLog();
$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, $auditLog->toSaveOptions());
}

...
$auditLog = new AuditLog();

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