From b82c7c790084bea8759eefcb1c3457906fde7bfd Mon Sep 17 00:00:00 2001 From: Chris Nizzardini Date: Sat, 24 Feb 2024 10:04:17 -0500 Subject: [PATCH] Fix double-save when save type is afterSave --- src/Model/Behavior/AuditLogBehavior.php | 2 -- .../Model/Behavior/AuditLogBehaviorTest.php | 36 +++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/Model/Behavior/AuditLogBehavior.php b/src/Model/Behavior/AuditLogBehavior.php index 568ceda..1c0b08c 100644 --- a/src/Model/Behavior/AuditLogBehavior.php +++ b/src/Model/Behavior/AuditLogBehavior.php @@ -55,8 +55,6 @@ public function implementedEvents(): array 'Model.beforeDelete' => 'injectTracking', 'Model.afterSave' => 'afterSave', 'Model.afterDelete' => 'afterDelete', - 'Model.afterSaveCommit' => 'afterCommit', - 'Model.afterDeleteCommit' => 'afterCommit', ]; if (Configure::read('AuditStash.saveType') !== 'afterSave') { diff --git a/tests/TestCase/Model/Behavior/AuditLogBehaviorTest.php b/tests/TestCase/Model/Behavior/AuditLogBehaviorTest.php index af9ea8b..5b93712 100644 --- a/tests/TestCase/Model/Behavior/AuditLogBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/AuditLogBehaviorTest.php @@ -7,6 +7,7 @@ use AuditStash\Event\AuditCreateEvent; use AuditStash\Event\AuditUpdateEvent; use AuditStash\Model\Behavior\AuditLogBehavior; +use Cake\Core\Configure; use Cake\Event\Event; use Cake\ORM\Entity; use Cake\ORM\Table; @@ -28,7 +29,13 @@ public function setUp(): void ]); } - public function testOnSaveCreateWithWithelist() + public function tearDown(): void + { + parent::tearDown(); + Configure::write('AuditStash.saveType', null); + } + + public function testOnSaveCreateWithWhitelist() { $data = [ 'id' => 13, @@ -55,7 +62,7 @@ public function testOnSaveCreateWithWithelist() $this->assertInstanceOf(AuditCreateEvent::class, $result); } - public function testOnSaveUpdateWithWithelist() + public function testOnSaveUpdateWithWhitelist() { $data = [ 'id' => 13, @@ -160,4 +167,29 @@ public function testSaveWithFieldsFromSchema() $this->assertEquals('articles', $result->getSourceName()); $this->assertInstanceOf(AuditCreateEvent::class, $result); } + + /** + * @dataProvider dataProviderForSaveType + */ + public function testImplementedEvents(?string $saveType): void + { + Configure::write('AuditStash.saveType', $saveType); + $events = (new AuditLogBehavior(new Table()))->implementedEvents(); + if ($saveType === 'afterSave') { + $this->assertArrayNotHasKey('Model.afterSaveCommit', $events); + $this->assertArrayNotHasKey('Model.afterDeleteCommit', $events); + } else { + $this->assertArrayHasKey('Model.afterSaveCommit', $events); + $this->assertArrayHasKey('Model.afterDeleteCommit', $events); + } + } + + public static function dataProviderForSaveType(): array + { + return [ + ['afterSave'], + ['afterCommit'], + [null], + ]; + } }