Skip to content

Commit 116401b

Browse files
committed
Hooks: Centrally prevent duplicate hook registration
1 parent 0eff254 commit 116401b

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

src/Hooks.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ public function register($hook, $callback, $priority = 0) {
5555
$this->hooks[$hook][$priority] = [];
5656
}
5757

58-
$this->hooks[$hook][$priority][] = $callback;
58+
if (!in_array($callback, $this->hooks[$hook][$priority], TRUE)) {
59+
$this->hooks[$hook][$priority][] = $callback;
60+
}
5961
}
6062

6163
/**

tests/HooksTest.php

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,70 @@ public function testRegister() {
9797
);
9898
}
9999

100+
/**
101+
* Technical test to verify the functionality of the Hooks::register() method.
102+
*
103+
* @covers ::register
104+
*
105+
* @return void
106+
*/
107+
public function testRegisterDuplicateHook() {
108+
// Verify initial state or the hooks property.
109+
$this->assertSame(
110+
[],
111+
$this->getPropertyValue($this->hooks, 'hooks'),
112+
'Initial state of $hooks is not an empty array'
113+
);
114+
115+
// Verify that the subkeys are created correctly when they don't exist yet.
116+
$this->hooks->register('hookname', [$this, 'dummyCallback1']);
117+
$this->assertSame(
118+
[
119+
'hookname' => [
120+
0 => [
121+
[$this, 'dummyCallback1'],
122+
],
123+
],
124+
],
125+
$this->getPropertyValue($this->hooks, 'hooks'),
126+
'Initial hook registration failed'
127+
);
128+
129+
// Verify that the subkeys are re-used when they already exist.
130+
$this->hooks->register('hookname', [$this, 'dummyCallback1']);
131+
$this->assertSame(
132+
[
133+
'hookname' => [
134+
0 => [
135+
[$this, 'dummyCallback1'],
136+
],
137+
],
138+
],
139+
$this->getPropertyValue($this->hooks, 'hooks'),
140+
'Registering the same callback on the same hook with the same priority does not register twice'
141+
);
142+
143+
/*
144+
* Verify that new subkeys are created when needed.
145+
* Also verifies that the input validation isn't too strict for the priority.
146+
*/
147+
$this->hooks->register('hookname', [$this, 'dummyCallback1'], '10');
148+
$this->assertSame(
149+
[
150+
'hookname' => [
151+
0 => [
152+
[$this, 'dummyCallback1'],
153+
],
154+
10 => [
155+
[$this, 'dummyCallback1'],
156+
],
157+
],
158+
],
159+
$this->getPropertyValue($this->hooks, 'hooks'),
160+
'Registering the same callback on a different priority for an existing hook succeeds'
161+
);
162+
}
163+
100164
/**
101165
* Technical test to verify and safeguard Hooks::register() accepts closure callbacks.
102166
*

0 commit comments

Comments
 (0)