Ensure tags are unique when adding and deleting them from bookmarks. (#1918)

* Ensure tags are unique when adding and deleting them from bookmarks.

* Fixed PHPCS issues with test script
This commit is contained in:
Keith Carangelo 2022-11-30 20:47:10 -05:00 committed by GitHub
parent e957f8fb23
commit 733b40446e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 59 additions and 2 deletions

View file

@ -524,7 +524,7 @@ public function renameTag(string $fromTag, string $toTag): void
*/ */
public function addTag(string $tag): self public function addTag(string $tag): self
{ {
return $this->setTags(array_merge($this->getTags(), [$tag])); return $this->setTags(array_unique(array_merge($this->getTags(), [$tag])));
} }
/** /**
@ -534,7 +534,7 @@ public function addTag(string $tag): self
*/ */
public function deleteTag(string $tag): void public function deleteTag(string $tag): void
{ {
if (($pos = array_search($tag, $this->tags ?? [])) !== false) { while (($pos = array_search($tag, $this->tags ?? [])) !== false) {
unset($this->tags[$pos]); unset($this->tags[$pos]);
$this->tags = array_values($this->tags); $this->tags = array_values($this->tags);
} }

View file

@ -262,6 +262,63 @@ public function testGetUrlWithNotValidProtocols()
$this->assertEquals($url, $bookmark->getUrl()); $this->assertEquals($url, $bookmark->getUrl());
} }
/**
* Test addTag() and DeleteTag()
*/
public function testAddDeleteTags()
{
$bookmark = new Bookmark();
$bookmark->addTag('tag1');
$this->assertEquals(
[
'tag1',
],
$bookmark->getTags()
);
// Ignore if tag is already present
$bookmark->addTag('tag2');
$bookmark->addTag('tag1');
$this->assertEquals(
[
'tag1',
'tag2',
],
$bookmark->getTags()
);
// Ignore deleting tags not present
$bookmark->deleteTag('tag5');
$this->assertEquals(
[
'tag1',
'tag2',
],
$bookmark->getTags()
);
// Delete multiples
$bookmark->setTags(['tag3', 'tag1', 'tag4', 'tag3', 'tag3', 'tag4']);
$bookmark->deleteTag('tag3');
$this->assertEquals(
[
'tag1',
'tag4',
'tag4',
],
$bookmark->getTags()
);
$bookmark->deleteTag('tag4');
$this->assertEquals(
[
'tag1',
],
$bookmark->getTags()
);
}
/** /**
* Test setTagsString() with exotic data * Test setTagsString() with exotic data
*/ */