Skip to content

Commit

Permalink
Clone arguments for SpyCall
Browse files Browse the repository at this point in the history
Prevents bugs where arguments can be mutated after the call.
  • Loading branch information
sirbrillig committed Sep 12, 2016
1 parent 5016f5e commit 92de74c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/Spies/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,16 @@ private static function do_vals_match( $a, $b ) {
}
return false;
}

public static function array_clone( $array ) {
return array_map( function( $element ) {
return ( ( is_array( $element ) )
? call_user_func( __FUNCTION__, $element )
: ( ( is_object( $element ) )
? clone $element
: $element
)
);
}, $array );
}
}
3 changes: 2 additions & 1 deletion src/Spies/Spy.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,8 @@ private function set_arguments( $args ) {
*
* You should not need to call this directly.
*/
private function record_function_call( $args ) {
private function record_function_call( $orig_args ) {
$args = Helpers::array_clone( $orig_args );
$this->call_record[] = new SpyCall( $args );
}

Expand Down
11 changes: 11 additions & 0 deletions tests/SpyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ public function test_spy_was_called_when_returns_false_if_the_spy_was_called_whe
} ) );
}

public function test_spy_was_called_when_uses_a_copy_of_the_arguments_as_they_were_when_the_call_occurred() {
$spy = \Spies\make_spy();
$obj = new \StdClass();
$obj->foo = 'original';
$spy( $obj );
$obj->foo = 'modified';
$this->assertTrue( $spy->was_called_when( function( $args ) {
return $args[0]->foo === 'original';
} ) );
}

public function test_spy_was_called_before_returns_true_if_called_before_target_spy() {
$spy_1 = \Spies\make_spy();
$spy_2 = \Spies\make_spy();
Expand Down

0 comments on commit 92de74c

Please sign in to comment.