From 0555d5f0abf8477aba2c48c0c44135ec144aed9f Mon Sep 17 00:00:00 2001 From: Nicos Panayides Date: Fri, 30 Aug 2024 12:07:53 +0300 Subject: [PATCH] Move change event creation to a protected functions to allow customization with custom event types and/or dynamic meta data --- src/Model/Behavior/AuditLogBehavior.php | 29 +++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/Model/Behavior/AuditLogBehavior.php b/src/Model/Behavior/AuditLogBehavior.php index b9bd3b4..130343c 100644 --- a/src/Model/Behavior/AuditLogBehavior.php +++ b/src/Model/Behavior/AuditLogBehavior.php @@ -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; @@ -109,6 +110,29 @@ 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 $changed Changed fields + * @param array $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; + + $auditEvent = new $auditEvent($transactionId, $primary, $this->_table->getTable(), $changed, $original, $entity); + + return $auditEvent; + } + /** * Calculates the changes done to the entity and stores the audit log event object into the * log queue inside the `_auditQueue` key in $options. @@ -157,11 +181,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());