jonnybarnes.uk/app/Observers/NoteObserver.php
Jonny Barnes 39a197ae7b
refactor: Refactor file headers and add Psalm suppressions
- Added Psalm suppression annotations to multiple controller classes
- Added PHPDoc comment blocks to seeders and factories
- Added comments to indicate unused classes and methods
- Removed unused annotations and imports
2023-07-28 11:48:07 +01:00

88 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\Note;
use App\Models\Tag;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
/**
* @todo Do we need psalm-suppress for these observer methods?
*/
class NoteObserver
{
/**
* Listen to the Note created event.
*
* @psalm-suppress PossiblyUnusedMethod
*/
public function created(Note $note): void
{
$text = Arr::get($note->getAttributes(), 'note');
if ($text === null) {
return;
}
$tags = $this->getTagsFromNote($text);
if (count($tags) === 0) {
return;
}
$tags->transform(function ($tag) {
return Tag::firstOrCreate(['tag' => $tag])->id;
})->toArray();
$note->tags()->attach($tags);
}
/**
* Listen to the Note updated event.
*
* @psalm-suppress PossiblyUnusedMethod
*/
public function updated(Note $note): void
{
$text = Arr::get($note->getAttributes(), 'note');
if ($text === null) {
return;
}
$tags = $this->getTagsFromNote($text);
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.
*
* @psalm-suppress PossiblyUnusedMethod
*/
public function deleting(Note $note): void
{
$note->tags()->detach();
}
/**
* Retrieve the tags from a notes text, tag for form #tag.
*/
private function getTagsFromNote(string $note): Collection
{
preg_match_all('/#([^\s<>]+)\b/', $note, $tags);
return collect($tags[1])->map(function ($tag) {
return Tag::normalize($tag);
})->unique();
}
}