Skip to content

Commit

Permalink
Tweaking actions & models to properly clean up DB after attachment de…
Browse files Browse the repository at this point in the history
…letion
  • Loading branch information
dominiclord committed Mar 18, 2020
1 parent 085b0c7 commit 5fa4012
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 12 deletions.
18 changes: 15 additions & 3 deletions src/Charcoal/Admin/Action/RemoveJoinAction.php
Expand Up @@ -15,6 +15,7 @@
use Charcoal\Loader\CollectionLoader;

// From 'charcoal-attachment'
use Charcoal\Attachment\Object\Attachment;
use Charcoal\Attachment\Object\Join;

/**
Expand Down Expand Up @@ -72,11 +73,22 @@ public function run(RequestInterface $request, ResponseInterface $response)
->addFilter('attachment_id', $attachmentId)
->addFilter('group', $group);

$existing_joins = $loader->load();
$existingJoins = $loader->load();

// Should be just one, tho.
foreach ($existing_joins as $j) {
$j->delete();
foreach ($existingJoins as $joinModel) {
$joinModel->delete();
}

// Try loading the attachment
try {
$attachment = $this->modelFactory()->create(Attachment::class)->load($attachmentId);
if ($attachment['id'] !== null) {
$attachment->delete();
}
} catch (Exception $error) {
$this->setSuccess(false);
return $response;
}

$this->setSuccess(true);
Expand Down
16 changes: 7 additions & 9 deletions src/Charcoal/Attachment/Object/Attachment.php
Expand Up @@ -26,7 +26,6 @@
// From 'charcoal-attachment'
use Charcoal\Attachment\Interfaces\AttachableInterface;
use Charcoal\Attachment\Interfaces\AttachmentContainerInterface;

use Charcoal\Attachment\Object\File;
use Charcoal\Attachment\Object\Image;
use Charcoal\Attachment\Object\Text;
Expand Down Expand Up @@ -923,15 +922,14 @@ public function setPresenter($presenter)
*/
public function preDelete()
{
$attId = $this->id();
$joinProto = $this->modelFactory()->get(Join::class);
$loader = $this->collectionLoader();
$loader->setModel($joinProto);

$collection = $loader->addFilter('attachment_id', $attId)->load();
$joinCollection = $this->collectionLoader()
->reset()
->setModel(Join::class)
->addFilter('attachment_id', $this['id'])
->load();

foreach ($collection as $obj) {
$obj->delete();
foreach ($joinCollection as $joinModel) {
$joinModel->delete();
}

return parent::preDelete();
Expand Down
15 changes: 15 additions & 0 deletions src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
Expand Up @@ -341,6 +341,21 @@ public function removeAttachmentJoins()
return true;
}

/**
* Delete the objects associated to the current object.
*
* @param array $options Filter the attachments by an option list.
* @return boolean
*/
public function deleteAttachments(array $options = [])
{
foreach ($this->getAttachments($options) as $attachment) {
$attachment->delete();
}

return true;
}

/**
* Retrieve the attachment widget.
*
Expand Down

0 comments on commit 5fa4012

Please sign in to comment.