Skip to content

Commit

Permalink
Hooks::dispatch(): modernize dynamic function call
Browse files Browse the repository at this point in the history
... by replacing the `call_user_func_array()` with a variable function call in combination with the spread operator.

Includes adding a dedicated test to safeguard that this change does not break the handling of references when passed as part of the `$parameters` to dispatch.
  • Loading branch information
jrfnl committed Nov 8, 2021
1 parent 91fbb1f commit 7d5014d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Hooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function dispatch($hook, $parameters = array()) {

foreach ($this->hooks[$hook] as $priority => $hooked) {
foreach ($hooked as $callback) {
call_user_func_array($callback, $parameters);
$callback(...$parameters);
}
}

Expand Down
34 changes: 34 additions & 0 deletions tests/HooksTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,29 @@ public function testDispatchWithMultipleRegisteredHooks() {
$this->assertTrue($this->hooks->dispatch('hook_b', array(10, 'text')));
}

/**
* Technical test to verify that the dispatch method handles parameters passed by reference correctly.
*
* @covers ::dispatch
*
* @return void
*/
public function testDispatchHandlesParametersPassedByReference() {
$this->hooks->register('hookname', array($this, 'dummyCallbackExpectingReferences'));
$url = 'original';
$headers = array('original');
$unchanged = 'original';
$not_a_reference = 'original';

$this->assertTrue($this->hooks->dispatch('hookname', array(&$url, &$headers, &$unchanged, $not_a_reference)));

// Verify that the variables were updated by reference (when passed as reference).
$this->assertSame('changed', $url);
$this->assertSame(array('changed'), $headers);
$this->assertSame('original', $unchanged);
$this->assertSame('original', $not_a_reference);
}

/**
* Technical test to verify that the dispatch method doesn't break on PHP 8.0 when passed an associative array.
*
Expand Down Expand Up @@ -374,4 +397,15 @@ public function dummyCallback1() {}
* @return void
*/
public function dummyCallback2() {}

/**
* Dummy callback method.
*
* @return void
*/
public function dummyCallbackExpectingReferences(&$url, &$headers, &$unchanged, $not_a_reference) {
$url = 'changed';
$headers = array('changed');
$not_a_reference = 'changed';
}
}

0 comments on commit 7d5014d

Please sign in to comment.