Skip to content

Commit

Permalink
Ability to disable cascading for trash/restore
Browse files Browse the repository at this point in the history
  • Loading branch information
kolorafa committed Aug 28, 2024
1 parent 79ac785 commit 7c73095
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ item, you can just attach the behavior to the related table classes, and set the
This works on relationships where the item being deleted in the owning side of
the relationship. Which means that the related table should contain the foreign key.

If you want to cascade normal (purge) deletion, but not to cascade trash/restore then:
```php
// in the initialize() method
$this->addBehavior('Muffin/Trash.Trash', [
'cascadeTrashAndRestore' => false,
]);
```

### Custom Finders

- **onlyTrashed** - helps getting only those trashed records.
Expand Down
2 changes: 2 additions & 0 deletions src/Model/Behavior/TrashBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class TrashBehavior extends Behavior
'Model.beforeDelete',
'Model.beforeFind',
],
'cascadeTrashAndRestore' => true,
];

/**
Expand Down Expand Up @@ -388,6 +389,7 @@ protected function _isRecursable(Association $association, Table $table): bool
$association->getTarget()->hasBehavior('Trash')
|| $association->getTarget()->hasBehavior(static::class)
)
&& $this->getConfig('cascadeTrashAndRestore')
&& $association->isOwningSide($table)
&& $association->getDependent()
&& $association->getCascadeCallbacks();
Expand Down
32 changes: 32 additions & 0 deletions tests/TestCase/Model/Behavior/TrashBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,38 @@ public function testCascadingTrash()
$this->assertInstanceOf(DateTime::class, $article->comments[0]->trashed);
}

/**
* When cascadeTrashAndRestore = false
* Ensure that when trashing it will not cascade into related dependent records
*
* @return void
*/
public function testDisabledCascadingForTrash()
{
$association = $this->Articles->Comments;
$association->setDependent(true);
$association->setCascadeCallbacks(true);

// disable cascade trash/restore
$this->Articles->behaviors()->get('Trash')->setConfig('cascadeTrashAndRestore', false);

$article = $this->Articles->get(1);
$this->Articles->trash($article);

$article = $this->Articles->find('withTrashed')
->where(['Articles.id' => 1])
->contain(['Comments' => [
'finder' => 'withTrashed',
]])
->first();

$this->assertNotEmpty($article->trashed);
$this->assertInstanceOf(DateTime::class, $article->trashed);

// expect not trashed
$this->assertEmpty($article->comments[0]->trashed);
}

public function testCascadingUntrashOptionsArePassedToSave()
{
$association = $this->Articles->Comments;
Expand Down

0 comments on commit 7c73095

Please # to comment.