From c359c85b0846f5f37b3406ba28281982d537dee4 Mon Sep 17 00:00:00 2001 From: Mark Redeman Date: Sat, 13 Dec 2014 13:40:03 +0100 Subject: [PATCH] Added ability to call methods on entity via presenter --- spec/Laracasts/Presenter/PresenterSpec.php | 50 ++++++++++++++++++++++ src/Laracasts/Presenter/Presenter.php | 19 +++++++- 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 spec/Laracasts/Presenter/PresenterSpec.php diff --git a/spec/Laracasts/Presenter/PresenterSpec.php b/spec/Laracasts/Presenter/PresenterSpec.php new file mode 100644 index 0000000..3ec4c6e --- /dev/null +++ b/spec/Laracasts/Presenter/PresenterSpec.php @@ -0,0 +1,50 @@ +beAnInstanceOf('spec\Laracasts\Presenter\ExamplePresenter'); + $this->beConstructedWith(new ExampleEntity); + } + + function it_retrieves_properties_of_its_entity() + { + $foo = $this->foo->shouldEqual('bar');; + } + + function it_calls_methods_of_its_entity_if_the_method_is_not_defined() + { + $this->baz()->shouldReturn(['foo', 'bar']); + } + + function it_calls_methods_of_its_entity_if_the_method_is_not_defined_and_passes_the_arguments() + { + $this->multiply(1, 2, 3)->shouldReturn(6); + } +} + +class ExampleEntity { + public $foo = 'bar'; + + public function baz() + { + return ['foo', 'bar']; + } + + public function multiply($x, $y, $z) + { + return $x * $y * $z; + } +} + +class ExamplePresenter extends Presenter { + +} \ No newline at end of file diff --git a/src/Laracasts/Presenter/Presenter.php b/src/Laracasts/Presenter/Presenter.php index 54c4cb7..047722c 100644 --- a/src/Laracasts/Presenter/Presenter.php +++ b/src/Laracasts/Presenter/Presenter.php @@ -31,4 +31,21 @@ public function __get($property) return $this->entity->{$property}; } -} \ No newline at end of file + /** + * Allow for method-style retrieval + * + * @param $method + * @param $arguments + * @return mixed + */ + public function __call($method, $arguments) + { + if (method_exists($this->entity, $method)) + { + return call_user_func_array([$this->entity, $method], $arguments); + } + + throw new \Exception("Method not found on presenter or its entity."); + } + +} \ No newline at end of file