Skip to content

Commit

Permalink
Merge pull request #87 from QoboLtd/flexible-events
Browse files Browse the repository at this point in the history
Move change event creation to a protected function
  • Loading branch information
dereuromark authored Aug 30, 2024
2 parents 59ae3c1 + fe5f3b7 commit 5cd5e4a
Showing 1 changed file with 30 additions and 4 deletions.
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

0 comments on commit 5cd5e4a

Please sign in to comment.