Skip to content

Commit

Permalink
Hooks: Centrally prevent duplicate hook registration
Browse files Browse the repository at this point in the history
  • Loading branch information
pprkut committed May 29, 2024
1 parent 0eff254 commit 116401b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Hooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ public function register($hook, $callback, $priority = 0) {
$this->hooks[$hook][$priority] = [];
}

$this->hooks[$hook][$priority][] = $callback;
if (!in_array($callback, $this->hooks[$hook][$priority], TRUE)) {

Check failure on line 58 in src/Hooks.php

View workflow job for this annotation

GitHub Actions / PHPCS

TRUE, FALSE and NULL must be lowercase; expected "true" but found "TRUE"
$this->hooks[$hook][$priority][] = $callback;
}
}

/**
Expand Down
64 changes: 64 additions & 0 deletions tests/HooksTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,70 @@ public function testRegister() {
);
}

/**
* Technical test to verify the functionality of the Hooks::register() method.
*
* @covers ::register
*
* @return void
*/
public function testRegisterDuplicateHook() {
// Verify initial state or the hooks property.
$this->assertSame(
[],
$this->getPropertyValue($this->hooks, 'hooks'),
'Initial state of $hooks is not an empty array'
);

// Verify that the subkeys are created correctly when they don't exist yet.
$this->hooks->register('hookname', [$this, 'dummyCallback1']);
$this->assertSame(
[
'hookname' => [
0 => [
[$this, 'dummyCallback1'],
],
],
],
$this->getPropertyValue($this->hooks, 'hooks'),
'Initial hook registration failed'
);

// Verify that the subkeys are re-used when they already exist.
$this->hooks->register('hookname', [$this, 'dummyCallback1']);
$this->assertSame(
[
'hookname' => [
0 => [
[$this, 'dummyCallback1'],
],
],
],
$this->getPropertyValue($this->hooks, 'hooks'),
'Registering the same callback on the same hook with the same priority does not register twice'
);

/*
* Verify that new subkeys are created when needed.
* Also verifies that the input validation isn't too strict for the priority.
*/
$this->hooks->register('hookname', [$this, 'dummyCallback1'], '10');
$this->assertSame(
[
'hookname' => [
0 => [
[$this, 'dummyCallback1'],
],
10 => [
[$this, 'dummyCallback1'],
],
],
],
$this->getPropertyValue($this->hooks, 'hooks'),
'Registering the same callback on a different priority for an existing hook succeeds'
);
}

/**
* Technical test to verify and safeguard Hooks::register() accepts closure callbacks.
*
Expand Down

0 comments on commit 116401b

Please sign in to comment.