Skip to content

Commit 992c332

Browse files
authored
Added magic __isset check for presenter to work for objects properties (#59)
1 parent c0f076c commit 992c332

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/Presenter.php

+19
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,25 @@ public function __get($attribute)
139139
return $this->model->{$attribute};
140140
}
141141

142+
/**
143+
* Dynamically check a property exists on the underlying object.
144+
*
145+
* @param mixed $attribute
146+
* @return bool
147+
*/
148+
public function __isset($attribute)
149+
{
150+
$method = $this->getStudlyAttributeMethod($attribute);
151+
152+
if (method_exists($this, $method)) {
153+
$value = $this->{$method}($this->model);
154+
155+
return ! is_null($value);
156+
}
157+
158+
return isset($this->model->{$attribute});
159+
}
160+
142161
/**
143162
* Convert the Presenter to a string.
144163
*

tests/PresenterTest.php

+40
Original file line numberDiff line numberDiff line change
@@ -449,4 +449,44 @@ public function output_keys_cannot_be_unset_via_array_access()
449449

450450
unset($presenter['email']);
451451
}
452+
453+
/** @test */
454+
public function can_check_isset_on_presenter_for_model_attribute()
455+
{
456+
$presenter = factory(User::class)
457+
->create(['name' => 'David Hemphill'])
458+
->present(UserProfilePresenter::class);
459+
460+
$this->assertTrue(isset($presenter->name));
461+
}
462+
463+
/** @test */
464+
public function can_check_isset_on_presenter_for_accessor()
465+
{
466+
$user = factory(User::class)->create();
467+
$presenter = new class($user) extends Presenter
468+
{
469+
public function getSayHelloAttribute()
470+
{
471+
return 'Hello from the Presenter!';
472+
}
473+
};
474+
475+
$this->assertTrue(isset($presenter->say_hello));
476+
}
477+
478+
/** @test */
479+
public function can_check_isset_is_false_on_presenter_for_accessor_if_returns_null()
480+
{
481+
$user = factory(User::class)->create();
482+
$presenter = new class($user) extends Presenter
483+
{
484+
public function getSayHelloAttribute()
485+
{
486+
return null;
487+
}
488+
};
489+
490+
$this->assertFalse(isset($presenter->say_hello));
491+
}
452492
}

0 commit comments

Comments
 (0)