Delete associated notifications when deleting discussions, posts, and users. fixes #1380

This commit is contained in:
Toby Zerner 2018-11-11 16:59:24 +10:30
parent 6d14d0c39b
commit bf8bc0222f
4 changed files with 45 additions and 0 deletions

View File

@ -21,6 +21,7 @@ use Flarum\Discussion\Event\Restored;
use Flarum\Discussion\Event\Started;
use Flarum\Event\GetModelIsPrivate;
use Flarum\Foundation\EventGeneratorTrait;
use Flarum\Notification\Notification;
use Flarum\Post\MergeableInterface;
use Flarum\Post\Post;
use Flarum\User\User;
@ -97,8 +98,18 @@ class Discussion extends AbstractModel
{
parent::boot();
static::deleting(function (Discussion $discussion) {
Notification::whereSubjectModel(Post::class)
->whereIn('subject_id', function ($query) use ($discussion) {
$query->select('id')->from('posts')->where('discussion_id', $discussion->id);
})
->delete();
});
static::deleted(function (Discussion $discussion) {
$discussion->raise(new Deleted($discussion));
Notification::whereSubject($discussion)->delete();
});
static::saving(function (Discussion $discussion) {

View File

@ -169,6 +169,35 @@ class Notification extends AbstractModel
});
}
/**
* Scope the query to include only notifications that have the given
* subject.
*
* @param Builder $query
* @param object $model
*/
public function scopeWhereSubject(Builder $query, $model)
{
$query->whereSubjectModel(get_class($model))
->where('subject_id', $model->id);
}
/**
* Scope the query to include only notification types that use the given
* subject model.
*
* @param Builder $query
* @param string $class
*/
public function scopeWhereSubjectModel(Builder $query, string $class)
{
$notificationTypes = array_filter(Notification::getSubjectModels(), function ($modelClass) use ($class) {
return $modelClass === $class or is_subclass_of($class, $modelClass);
});
$query->whereIn('type', array_keys($notificationTypes));
}
/**
* Get the type-to-subject-model map.
*

View File

@ -17,6 +17,7 @@ use Flarum\Discussion\Discussion;
use Flarum\Event\GetModelIsPrivate;
use Flarum\Event\ScopeModelVisibility;
use Flarum\Foundation\EventGeneratorTrait;
use Flarum\Notification\Notification;
use Flarum\Post\Event\Deleted;
use Flarum\User\User;
use Illuminate\Database\Eloquent\Builder;
@ -106,6 +107,8 @@ class Post extends AbstractModel
static::deleted(function (Post $post) {
$post->raise(new Deleted($post));
Notification::whereSubject($post)->delete();
});
static::addGlobalScope(new RegisteredTypesScope);

View File

@ -125,6 +125,8 @@ class User extends AbstractModel
static::deleted(function (User $user) {
$user->raise(new Deleted($user));
Notification::whereSubject($user)->delete();
});
static::$dispatcher->dispatch(