use model observer to manage tagging of notes

This commit is contained in:
Jonny Barnes 2017-11-09 11:31:17 +00:00
parent 14cba19903
commit 467b607774
3 changed files with 79 additions and 17 deletions

View file

@ -462,7 +462,7 @@ class Note extends Model
$name = str_replace('#', '', $name);
$replacements[$name] =
'<a rel="tag" class="p-category" href="/notes/tagged/'
. Tag::normalizeTag($name)
. Tag::normalize($name)
. '">#'
. $name
. '</a>';

View file

@ -0,0 +1,76 @@
<?php
namespace App\Observers;
use App\{Note, Tag};
class NoteObserver
{
/**
* Listen to the Note created event.
*
* @param \App\Note $note
* @return void
*/
public function created(Note $note)
{
$tags = $this->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();
}
}

View file

@ -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(