From 992c3328b925612089f19eafd5ae0c8c3c588e41 Mon Sep 17 00:00:00 2001 From: Matthew Williams Date: Wed, 6 Jul 2022 21:37:10 +0100 Subject: [PATCH] Added magic __isset check for presenter to work for objects properties (#59) --- src/Presenter.php | 19 +++++++++++++++++++ tests/PresenterTest.php | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/Presenter.php b/src/Presenter.php index f582a04..e1cb3ab 100644 --- a/src/Presenter.php +++ b/src/Presenter.php @@ -139,6 +139,25 @@ public function __get($attribute) return $this->model->{$attribute}; } + /** + * Dynamically check a property exists on the underlying object. + * + * @param mixed $attribute + * @return bool + */ + public function __isset($attribute) + { + $method = $this->getStudlyAttributeMethod($attribute); + + if (method_exists($this, $method)) { + $value = $this->{$method}($this->model); + + return ! is_null($value); + } + + return isset($this->model->{$attribute}); + } + /** * Convert the Presenter to a string. * diff --git a/tests/PresenterTest.php b/tests/PresenterTest.php index dd10bcc..be1e048 100644 --- a/tests/PresenterTest.php +++ b/tests/PresenterTest.php @@ -449,4 +449,44 @@ public function output_keys_cannot_be_unset_via_array_access() unset($presenter['email']); } + + /** @test */ + public function can_check_isset_on_presenter_for_model_attribute() + { + $presenter = factory(User::class) + ->create(['name' => 'David Hemphill']) + ->present(UserProfilePresenter::class); + + $this->assertTrue(isset($presenter->name)); + } + + /** @test */ + public function can_check_isset_on_presenter_for_accessor() + { + $user = factory(User::class)->create(); + $presenter = new class($user) extends Presenter + { + public function getSayHelloAttribute() + { + return 'Hello from the Presenter!'; + } + }; + + $this->assertTrue(isset($presenter->say_hello)); + } + + /** @test */ + public function can_check_isset_is_false_on_presenter_for_accessor_if_returns_null() + { + $user = factory(User::class)->create(); + $presenter = new class($user) extends Presenter + { + public function getSayHelloAttribute() + { + return null; + } + }; + + $this->assertFalse(isset($presenter->say_hello)); + } }