From 467b60777437c1bec9d7a473781c3969e1fb0a36 Mon Sep 17 00:00:00 2001 From: Jonny Barnes Date: Thu, 9 Nov 2017 11:31:17 +0000 Subject: [PATCH] use model observer to manage tagging of notes --- app/Note.php | 2 +- app/Observers/NoteObserver.php | 76 ++++++++++++++++++++++++++++++++++ app/Tag.php | 18 +------- 3 files changed, 79 insertions(+), 17 deletions(-) create mode 100644 app/Observers/NoteObserver.php diff --git a/app/Note.php b/app/Note.php index dc932019..ef94e327 100644 --- a/app/Note.php +++ b/app/Note.php @@ -462,7 +462,7 @@ class Note extends Model $name = str_replace('#', '', $name); $replacements[$name] = ''; diff --git a/app/Observers/NoteObserver.php b/app/Observers/NoteObserver.php new file mode 100644 index 00000000..4b9dc1dd --- /dev/null +++ b/app/Observers/NoteObserver.php @@ -0,0 +1,76 @@ +getTagsFromNote($note->getAttributes()['note']); + + if (count($tags) === 0) { + return; + } + + $tags->transform(function ($tag) { + return Tag::firstOrCreate(['tag' => $tag]); + }); + + $note->tags()->attach($tags->map(function ($tag) { + return $tag->id; + })); + } + + /** + * Listen to the Note updated event. + * + * @param \App\Note $Note + * @return void + */ + public function updated(Note $note) + { + $tags = $this->getTagsFromNote($note->getAttributes()['note']); + if (count($tags) === 0) { + return; + } + + $tags->transform(function ($tag) { + return Tag::firstOrCreate(['tag' => $tag]); + }); + + $note->tags()->sync($tags->map(function ($tag) { + return $tag->id; + })); + } + + /** + * Listen to the Note deleting event. + * + * @param \App\Note $note + * @return void + */ + public function deleting(Note $note) + { + $note->tags()->detach(); + } + + public function getTagsFromNote($note) + { + preg_match_all('/#([^\s<>]+)\b/', $note, $tags); + if (array_get($tags, '1') === null) { + return []; + } + + return collect($tags[1])->map(function ($tag) { + return Tag::normalize($tag); + })->unique(); + } +} diff --git a/app/Tag.php b/app/Tag.php index 0e7b6e3e..8b876d2e 100644 --- a/app/Tag.php +++ b/app/Tag.php @@ -6,13 +6,6 @@ use Illuminate\Database\Eloquent\Model; class Tag extends Model { - /** - * The database table used by the model. - * - * @var string - */ - protected $table = 'tags'; - /** * Define the relationship with tags. * @@ -31,13 +24,6 @@ class Tag extends Model return $this->belongsToMany('App\Bookmark'); } - /** - * The attributes excluded from the model's JSON form. - * - * @var array - */ - protected $hidden = ['deleted']; - /** * We shall set a blacklist of non-modifiable model attributes. * @@ -52,7 +38,7 @@ class Tag extends Model */ public function setTagAttribute($value) { - $this->attributes['tag'] = $this->normalizeTag($value); + $this->attributes['tag'] = $this->normalize($value); } /** @@ -61,7 +47,7 @@ class Tag extends Model * * @param string */ - public static function normalizeTag($tag) + public static function normalize($tag) { return mb_strtolower( preg_replace(