From 2d7c995738b4ff5106a19b787035a4f0f6e1745b Mon Sep 17 00:00:00 2001 From: fr0tt <33751346+fr0tt@users.noreply.github.com> Date: Fri, 11 Aug 2023 12:43:56 +0200 Subject: [PATCH] fix and test tag im/export --- app/Helpers/NetscapeBookmarkDecoder.php | 26 ++++++++++++++++++++----- app/Helpers/NetscapeBookmarkEncoder.php | 4 +++- tests/Feature/ImAndExportTest.php | 12 ++++++++++-- tests/bookmarks.html | 2 +- 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/app/Helpers/NetscapeBookmarkDecoder.php b/app/Helpers/NetscapeBookmarkDecoder.php index e829640..2e53b8f 100644 --- a/app/Helpers/NetscapeBookmarkDecoder.php +++ b/app/Helpers/NetscapeBookmarkDecoder.php @@ -4,6 +4,8 @@ use App\Models\Collection; use App\Services\PostService; +use App\Services\TagService; +use Illuminate\Support\Str; /* * This file is heavily inspired by: @@ -38,6 +40,7 @@ class NetscapeBookmarkDecoder { protected $items; private PostService $postService; + private TagService $tagService; private $userId; const TRUE_PATTERN = 'y|yes|on|checked|ok|1|true|array|\+|okay|yes|t|one'; @@ -50,6 +53,7 @@ class NetscapeBookmarkDecoder public function __construct(int $userId) { $this->postService = new PostService(); + $this->tagService = new TagService(); $this->userId = $userId; } @@ -119,10 +123,11 @@ public function parseString(string $bookmarkString, int $collectionId): array $tags = array(); if (preg_match('/(tags?|labels?|folders?)="(.*?)"/i', $line, $m7)) { - $tags = array_merge( - $tags, - explode(' ', strtr($m7[2], ',', ' ')) - ); + if (Str::contains($m7[2], ',')) { + $tags = preg_split('/\s*,\s*/', $m7[2]); + } else { + $tags = preg_split('/\s+/', $m7[2]); + } } $this->items[$i]['tags'] = $tags; @@ -268,9 +273,20 @@ private function createPost($title, $collectionId, $url, $description, $tags = n $url, $collectionId, $description, - count($tags) > 0 ? $tags : null, + $this->createTags($tags), $this->userId, ); } + private function createTags(array $tagNames): array|null + { + if (count($tagNames) === 0) { + return null; + } + return array_map(function ($tagName) { + $tag = $this->tagService->saveTag($tagName, $this->userId); + return $tag->id; + }, $tagNames); + } + } diff --git a/app/Helpers/NetscapeBookmarkEncoder.php b/app/Helpers/NetscapeBookmarkEncoder.php index 0c1a866..c057342 100644 --- a/app/Helpers/NetscapeBookmarkEncoder.php +++ b/app/Helpers/NetscapeBookmarkEncoder.php @@ -107,12 +107,14 @@ private function getPosts(int $collectionId = null, int $level): string $createdAt = strtotime($post->created_at); $updatedAt = strtotime($post->updated_at); $description = trim($post->description); + $tags = $post->tags->implode('name', ', '); + $content .= "{$this->tabs($level)}" . "
-