Skip to content

Commit

Permalink
Added magic __isset check for presenter to work for objects properties (
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewnw authored Jul 6, 2022
1 parent c0f076c commit 992c332
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Presenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
40 changes: 40 additions & 0 deletions tests/PresenterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit 992c332

Please sign in to comment.