diff --git a/components/Link/Link.php b/components/Link/Link.php index 15632499d5..d8b0d5da43 100644 --- a/components/Link/Link.php +++ b/components/Link/Link.php @@ -35,6 +35,22 @@ use InvalidArgumentException; class Link extends Component { + /** + * Note that this persists both a Link and a NoteToLink + * + * @return [Entity\Link, NoteToLink] + */ + public static function maybeCreateLink(string $url, int $note_id): array + { + try { + $link = Entity\Link::getOrCreate($url); + DB::persist($note_link = NoteToLink::create(['link_id' => $link->getId(), 'note_id' => $note_id])); + return ['link' => $link, 'note_to_link' => $note_link]; + } catch (InvalidArgumentException) { + return ['link' => null, 'note_to_link' => null]; + } + } + /** * Extract URLs from $content and create the appropriate Link and NoteToLink entities */ @@ -49,12 +65,7 @@ class Link extends Component if (\in_array($match, $ignore)) { continue; } - try { - $link_id = Entity\Link::getOrCreate($match)->getId(); - DB::persist(NoteToLink::create(['link_id' => $link_id, 'note_id' => $note->getId()])); - } catch (InvalidArgumentException) { - continue; - } + self::maybeCreateLink($match, $note_id); } } return Event::next; diff --git a/components/Tag/Tag.php b/components/Tag/Tag.php index 059fbd70b4..81c60d0ea0 100644 --- a/components/Tag/Tag.php +++ b/components/Tag/Tag.php @@ -67,6 +67,25 @@ class Tag extends Component return Event::next; } + public static function maybeCreateTag(string $tag, int $note_id, ?int $lang_id): ?NoteTag + { + if (!self::validate($tag)) { + return null; // Ignore invalid tag candidates + } + $canonical_tag = self::canonicalTag($tag, \is_null($lang_id) ? null : Language::getById($lang_id)->getLocale()); + DB::persist($note_tag = NoteTag::create([ + 'tag' => $tag, + 'canonical' => $canonical_tag, + 'note_id' => $note_id, + 'use_canonical' => $extra_args['tag_use_canonical'] ?? false, + 'language_id' => $lang_id, + ])); + foreach (self::cacheKeys($canonical_tag) as $key) { + Cache::delete($key); + } + return $note_tag; + } + /** * Process note by extracting any tags present */ @@ -82,21 +101,7 @@ class Tag extends Component $matched_tags = array_unique(F\map($matched_tags, fn ($m) => $m[2])); foreach ($matched_tags as $match) { $tag = self::extract($match); - if (!self::validate($tag)) { - continue; // Ignore invalid tag candidates - } - $canonical_tag = self::canonicalTag($tag, \is_null($lang_id = $note->getLanguageId()) ? null : Language::getById($lang_id)->getLocale()); - DB::persist(NoteTag::create([ - 'tag' => $tag, - 'canonical' => $canonical_tag, - 'note_id' => $note->getId(), - 'use_canonical' => $extra_args['tag_use_canonical'] ?? false, - 'language_id' => $lang_id, - ])); - Cache::listPushLeft("tag-{$canonical_tag}", $note); - foreach (self::cacheKeys($canonical_tag) as $key) { - Cache::delete($key); - } + self::maybeCreateTag(tag: $tag, note_id: $note->getId(), lang_id: $note->getLanguageId()); } return Event::next; }