implement audit logger
This commit is contained in:
6 files changed
+161
-13
No files matched your search
@@ -0,0 +1,75 @@
|
||||
<?php namespace SokoWeb\Database;
|
||||
|
||||
use SokoWeb\Interfaces\Database\IAuditLogger;
|
||||
use SokoWeb\Interfaces\Database\IConnection;
|
||||
|
||||
abstract class AuditLoggerBase implements IAuditLogger
|
||||
{
|
||||
const LOG_TYPE_INSERT = 'insert';
|
||||
const LOG_TYPE_UPDATE = 'update';
|
||||
const LOG_TYPE_DELETE = 'delete';
|
||||
|
||||
private IConnection $connection;
|
||||
|
||||
private string $logTable;
|
||||
|
||||
public function __construct(IConnection $connection, string $logTable)
|
||||
{
|
||||
$this->connection = $connection;
|
||||
$this->logTable = $logTable;
|
||||
}
|
||||
|
||||
public function logInsert(string $localTable, $localId): void
|
||||
{
|
||||
$data = [
|
||||
'local_table' => $localTable,
|
||||
'local_id' => $localId,
|
||||
'type' => static::LOG_TYPE_INSERT,
|
||||
'modifier_id' => $this->getModifierId(),
|
||||
];
|
||||
|
||||
$query = 'INSERT INTO ' . Utils::backtick($this->logTable) . ' SET ' . Utils::generateColumnsWithBinding(array_keys($data));
|
||||
$stmt = $this->connection->prepare($query);
|
||||
$stmt->execute($data);
|
||||
}
|
||||
|
||||
public function logUpdate(string $localTable, $localId, array $diff): void
|
||||
{
|
||||
$data = [
|
||||
'local_table' => $localTable,
|
||||
'local_id' => $localId,
|
||||
'type' => static::LOG_TYPE_UPDATE,
|
||||
'modifier_id' => $this->getModifierId(),
|
||||
'column' => null,
|
||||
'old' => null,
|
||||
'new' => null,
|
||||
];
|
||||
|
||||
$query = 'INSERT INTO ' . Utils::backtick($this->logTable) . ' SET ' . Utils::generateColumnsWithBinding(array_keys($data));
|
||||
$stmt = $this->connection->prepare($query);
|
||||
|
||||
foreach ($diff as $name => $values) {
|
||||
$data['column'] = $name;
|
||||
$data['old'] = $values['old'];
|
||||
$data['new'] = $values['new'];
|
||||
$stmt->execute($data);
|
||||
}
|
||||
}
|
||||
|
||||
public function logDelete(string $localTable, $localId, array $attributes): void
|
||||
{
|
||||
$data = [
|
||||
'local_table' => $localTable,
|
||||
'local_id' => $localId,
|
||||
'type' => static::LOG_TYPE_DELETE,
|
||||
'modifier_id' => $this->getModifierId(),
|
||||
'old' => $attributes,
|
||||
];
|
||||
|
||||
$query = 'INSERT INTO ' . Utils::backtick($this->logTable) . ' SET ' . Utils::generateColumnsWithBinding(array_keys($data));
|
||||
$stmt = $this->connection->prepare($query);
|
||||
$stmt->execute($data);
|
||||
}
|
||||
|
||||
abstract protected function getModifierId();
|
||||
}
|
||||
Reference in new issue
Block a user