Skip to content

Commit

Permalink
Fix double-save when save type is afterSave
Browse files Browse the repository at this point in the history
  • Loading branch information
cnizzardini committed Feb 24, 2024
1 parent f098114 commit b82c7c7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
2 changes: 0 additions & 2 deletions src/Model/Behavior/AuditLogBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
36 changes: 34 additions & 2 deletions tests/TestCase/Model/Behavior/AuditLogBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -55,7 +62,7 @@ public function testOnSaveCreateWithWithelist()
$this->assertInstanceOf(AuditCreateEvent::class, $result);
}

public function testOnSaveUpdateWithWithelist()
public function testOnSaveUpdateWithWhitelist()
{
$data = [
'id' => 13,
Expand Down Expand Up @@ -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],
];
}
}

0 comments on commit b82c7c7

Please sign in to comment.