From 5b4357f1986c6dc5b7d9c7ed001a780b7f4acc07 Mon Sep 17 00:00:00 2001 From: Sergey Lukin Date: Wed, 5 Nov 2014 17:40:15 +0200 Subject: [PATCH] Allow setting properties after instantiation I find it more readable to assign properties/methods after instantiation, like so: ``` $stub = new s(); $stub->foo = 'bar'; $stub->callMe = function() {}; ``` This commit allows doing just that. --- README.md | 4 ++++ src/Nulpunkt/PhpStub/Stub.php | 5 +++++ test/Nulpunkt/PhpStub/StubTest.php | 14 ++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/README.md b/README.md index 740b71b..c24c1d5 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,13 @@ $stub = new Stub([ 'answer' => 42, 'callMe' => function($a) { return $a; } # Anything which is a callable ]); +$stub->foo = 'bar'; +$stub->myMethod = function() { return 50; }; echo $stub->answer(); # => 42 echo $stub->answer; # => 42 echo $stub->callMe('maybe'); # => 'maybe' +echo $stub->foo; # => 'bar' +echo $stub->myMethod(); # => 50 echo $stub->lol()->hey(); # => $stub // Different configurations diff --git a/src/Nulpunkt/PhpStub/Stub.php b/src/Nulpunkt/PhpStub/Stub.php index b397955..f85ae67 100644 --- a/src/Nulpunkt/PhpStub/Stub.php +++ b/src/Nulpunkt/PhpStub/Stub.php @@ -44,6 +44,11 @@ public function __get($name) } return null; } + + public function __set($name, $value) + { + $this->methods[$name] = $value; + } public function __isset($property) { diff --git a/test/Nulpunkt/PhpStub/StubTest.php b/test/Nulpunkt/PhpStub/StubTest.php index 29e478a..0564b2e 100644 --- a/test/Nulpunkt/PhpStub/StubTest.php +++ b/test/Nulpunkt/PhpStub/StubTest.php @@ -12,6 +12,20 @@ public function testThatAStubRespondToDefinedMethods() $this->assertSame(42, $stub->getId()); } + public function testThatMethodsCanBeAssignedAfterInstantiation() + { + $stub = new Stub(); + $stub->myMethod = function() { return 42; }; + $this->assertSame(42, $stub->myMethod()); + } + + public function testThatPropertiesCanBeAssignedAfterInstantiation() + { + $stub = new Stub(); + $stub->foo = 'bar'; + $this->assertSame('bar', $stub->foo); + } + public function testThatItHasAllProperties() { $stub = new Stub();