From 01c63b820ea9f892e2f744135e4c81a1911738cb Mon Sep 17 00:00:00 2001 From: Juan Pablo Barreto Date: Thu, 8 Sep 2022 13:32:26 +0200 Subject: [PATCH] feat: add TagCollection magic getter and call This supports calling `->twitter()->title()` or `twitter()->title` to get the title instead of `->twitter()->get('title')` --- src/Tags/TagCollection.php | 16 ++++++++++++++++ tests/Tags/TagCollectionTest.php | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/Tags/TagCollection.php b/src/Tags/TagCollection.php index 62a6c76..7b70d55 100644 --- a/src/Tags/TagCollection.php +++ b/src/Tags/TagCollection.php @@ -22,6 +22,22 @@ public function get(string $property) return $this->metadata[$property] ?? null; } + /** + * @return string|array|null + */ + public function __call(string $property, array $arguments) + { + return $this->get($property); + } + + /** + * @return string|array|null + */ + public function __get(string $property) + { + return $this->get($property); + } + public function toArray(): array { return $this->metadata; diff --git a/tests/Tags/TagCollectionTest.php b/tests/Tags/TagCollectionTest.php index c5151f1..eafccb2 100644 --- a/tests/Tags/TagCollectionTest.php +++ b/tests/Tags/TagCollectionTest.php @@ -65,4 +65,37 @@ public function test_it_should_convert_to_array(): void ], ], $og->toArray()); } + + public function test_magic_getter_and_call_work(): void + { + // Arrange + $metadata = [ + 'og:title' => 'My Title', + 'og:image' => [ + 'https://image.url/here.jpg', + 'https://image.url/here-2.jpg', + ], + ]; + + // Act + $og = new TagCollection('og:', $metadata); + + // Assert + $this->assertEquals('My Title', $og->title); + $this->assertEquals('My Title', $og->title()); + $this->assertEquals('My Title', $og->get('title')); + + $this->assertEquals([ + 'https://image.url/here.jpg', + 'https://image.url/here-2.jpg', + ], $og->image()); + $this->assertEquals([ + 'https://image.url/here.jpg', + 'https://image.url/here-2.jpg', + ], $og->image); + $this->assertEquals([ + 'https://image.url/here.jpg', + 'https://image.url/here-2.jpg', + ], $og->get('image')); + } }