Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move change event creation to a protected function #87

Merged
merged 3 commits into from
Aug 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/Model/Behavior/AuditLogBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use AuditStash\Event\AuditCreateEvent;
use AuditStash\Event\AuditDeleteEvent;
use AuditStash\Event\AuditUpdateEvent;
use AuditStash\Event\BaseEvent;
use AuditStash\Persister\ElasticSearchPersister;
use AuditStash\PersisterInterface;
use Cake\Core\Configure;
Expand Down Expand Up @@ -109,6 +110,34 @@ private function redactArray(array &$fields): void
}
}

/**
* Creates an audit event for the entity change.
*
* @param string $transactionId Transaction Id
* @param \Cake\Datasource\EntityInterface $entity Entity
* @param array<string, mixed> $changed Changed fields
* @param array<string, mixed> $original Original fields
* @return \AuditStash\Event\BaseEvent
*/
protected function createEvent(
string $transactionId,
EntityInterface $entity,
array $changed,
array $original
): BaseEvent {
$primary = $entity->extract((array)$this->_table->getPrimaryKey());
$auditEvent = $entity->isNew() ? AuditCreateEvent::class : AuditUpdateEvent::class;

return new $auditEvent(
$transactionId,
$primary,
$this->_table->getTable(),
$changed,
$original,
$entity
);
}

/**
* Calculates the changes done to the entity and stores the audit log event object into the
* log queue inside the `_auditQueue` key in $options.
Expand Down Expand Up @@ -157,11 +186,8 @@ public function afterSave(
$this->redactArray($changed);
$this->redactArray($original);

$primary = $entity->extract((array)$this->_table->getPrimaryKey());
$auditEvent = $entity->isNew() ? AuditCreateEvent::class : AuditUpdateEvent::class;

$transaction = $options['_auditTransaction'];
$auditEvent = new $auditEvent($transaction, $primary, $this->_table->getTable(), $changed, $original, $entity);
$auditEvent = $this->createEvent($transaction, $entity, $changed, $original);

if (!empty($options['_sourceTable'])) {
$auditEvent->setParentSourceName($options['_sourceTable']->getTable());
Expand Down
Loading