Skip to content

Commit

Permalink
Merge pull request #10 from bwaidelich/feature/tags-firstOfKey
Browse files Browse the repository at this point in the history
FEATURE: Add `Tags::firstOfKey` convenience method
  • Loading branch information
bwaidelich authored Sep 5, 2023
2 parents d462101 + 2591e50 commit 317d8a1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Types/Tags.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ public function merge(self|Tag $other): self
return self::fromArray(array_merge($this->tags, $other->tags));
}

public function firstOfKey(string $key): ?Tag
{
foreach ($this->tags as $tag) {
if ($tag->key === $key) {
return $tag;
}
}
return null;
}

public function contain(Tag $tag): bool
{
return array_key_exists($tag->toString(), $this->tags);
Expand Down
14 changes: 14 additions & 0 deletions tests/Unit/Types/TagsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,20 @@ public function test_merge(array $ids1, array $ids2, array $expectedResult): voi
self::assertTagsMatch($expectedResult, Tags::fromArray($ids1)->merge(Tags::fromArray($ids2)));
}

public function test_firstOfKey_returns_null_if_no_matching_tag_is_found(): void
{
$tags = Tags::fromArray(['foo:bar', 'bar:baz']);
self::assertNull($tags->firstOfKey('baz'));
}

public function test_firstOfKey_returns_first_matching_tag_if_exists(): void
{
$tags = Tags::fromArray(['foo:bar', 'bar:baz', 'bar:aaa']);
$tag = $tags->firstOfKey('bar');
self::assertInstanceOf(Tag::class, $tag);
self::assertSame('bar:aaa', $tag->toString());
}

public function test_contains_allows_checking_single_tags(): void
{
$ids = Tags::fromArray(['foo:bar', 'baz:foos']);
Expand Down

0 comments on commit 317d8a1

Please sign in to comment.