diff --git a/README.md b/README.md index 91d4994..0e4c9ff 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,9 @@ Now you can start setting up objects for method hooking. ```php class Test { - function testFunction($string) { - echo $string; - } + function testFunction($string) { + echo $string; + } } $obj = new Test(); \SciActive\Hook::hookObject($obj, 'Test->'); @@ -36,7 +36,7 @@ And modifying their method calls. ```php \SciActive\Hook::addCallback('Test->testFunction', -2, function(&$arguments, $name, &$object, &$function, &$data){ - $arguments[0] = 'New argument instead.'; + $arguments[0] = 'New argument instead.'; }); ``` diff --git a/src/HookOverride_extend.php b/src/HookOverride_extend.php index 8f21fa3..b2c648f 100644 --- a/src/HookOverride_extend.php +++ b/src/HookOverride_extend.php @@ -81,11 +81,20 @@ public function __clone() { } public function jsonSerialize() { - if (is_callable($this->_hookObject, 'jsonSerialize')) { - $args = func_get_args(); - return call_user_func_array(array($this->_hookObject, 'jsonSerialize'), $args); - } else { - return $this->_hookObject; + $_HOOK_arguments = func_get_args(); + $_HOOK_function = array($this->_hookObject, 'jsonSerialize'); + $_HOOK_data = array(); + \SciActive\Hook::runCallbacks($this->_hookPrefix.'jsonSerialize', $_HOOK_arguments, 'before', $this->_hookObject, $_HOOK_function, $_HOOK_data); + if ($_HOOK_arguments !== false) { + if (is_callable($this->_hookObject, 'jsonSerialize') && !empty($_HOOK_arguments)) { + $_HOOK_return = array(call_user_func_array($_HOOK_function, $_HOOK_arguments)); + } else { + $_HOOK_return = array($this->_hookObject); + } + \SciActive\Hook::runCallbacks($this->_hookPrefix.'jsonSerialize', $_HOOK_return, 'after', $this->_hookObject, $_HOOK_function, $_HOOK_data); + if ((array) $_HOOK_return === $_HOOK_return) { + return $_HOOK_return[0]; + } } } diff --git a/testing/tests/HookTest.php b/testing/tests/HookTest.php index 856ba92..60a02a0 100644 --- a/testing/tests/HookTest.php +++ b/testing/tests/HookTest.php @@ -100,6 +100,19 @@ public function testDataPassing($testModel) { $this->assertEquals(1, Hook::delCallbackByID('TestModel->testFunction', $ids[0])); } + /** + * @depends testHooking + */ + public function testJSONSerialization($testModel) { + $this->assertObjectNotHasAttribute('testJson', json_decode(json_encode($testModel))); + $ids = Hook::addCallback('TestModel->jsonSerialize', 1, function (&$return, $name, &$object, &$function, &$data) { + $return[0]->testJson = 'success'; + }); + $this->assertEquals('success', json_decode(json_encode($testModel))->testJson); + $this->assertEquals(1, Hook::delCallbackByID('TestModel->jsonSerialize', $ids[0])); + $this->assertEquals(0, count(Hook::getCallbacks()['TestModel->jsonSerialize'])); + } + /** * Do this one last, cause it leaves its callbacks. *