Complete test coverage of Hooks class
[lhc/web/wiklou.git] / includes / Hooks.php
1 <?php
2
3 /**
4 * A tool for running hook functions.
5 *
6 * Copyright 2004, 2005 Evan Prodromou <evan@wikitravel.org>.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 *
22 * @author Evan Prodromou <evan@wikitravel.org>
23 * @see hooks.txt
24 * @file
25 */
26
27 /**
28 * Hooks class.
29 *
30 * Used to supersede $wgHooks, because globals are EVIL.
31 *
32 * @since 1.18
33 */
34 class Hooks {
35 /**
36 * Array of events mapped to an array of callbacks to be run
37 * when that event is triggered.
38 */
39 protected static $handlers = [];
40
41 /**
42 * Attach an event handler to a given hook.
43 *
44 * @param string $name Name of hook
45 * @param callable $callback Callback function to attach
46 *
47 * @since 1.18
48 */
49 public static function register( $name, $callback ) {
50 if ( !isset( self::$handlers[$name] ) ) {
51 self::$handlers[$name] = [];
52 }
53
54 self::$handlers[$name][] = $callback;
55 }
56
57 /**
58 * Clears hooks registered via Hooks::register(). Does not touch $wgHooks.
59 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
60 *
61 * @param string $name The name of the hook to clear.
62 *
63 * @since 1.21
64 * @throws MWException If not in testing mode.
65 * @codeCoverageIgnore
66 */
67 public static function clear( $name ) {
68 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
69 throw new MWException( 'Cannot reset hooks in operation.' );
70 }
71
72 unset( self::$handlers[$name] );
73 }
74
75 /**
76 * Returns true if a hook has a function registered to it.
77 * The function may have been registered either via Hooks::register or in $wgHooks.
78 *
79 * @since 1.18
80 *
81 * @param string $name Name of hook
82 * @return bool True if the hook has a function registered to it
83 */
84 public static function isRegistered( $name ) {
85 global $wgHooks;
86 return !empty( $wgHooks[$name] ) || !empty( self::$handlers[$name] );
87 }
88
89 /**
90 * Returns an array of all the event functions attached to a hook
91 * This combines functions registered via Hooks::register and with $wgHooks.
92 *
93 * @since 1.18
94 *
95 * @param string $name Name of the hook
96 * @return array
97 */
98 public static function getHandlers( $name ) {
99 global $wgHooks;
100
101 if ( !self::isRegistered( $name ) ) {
102 return [];
103 } elseif ( !isset( self::$handlers[$name] ) ) {
104 return $wgHooks[$name];
105 } elseif ( !isset( $wgHooks[$name] ) ) {
106 return self::$handlers[$name];
107 } else {
108 return array_merge( self::$handlers[$name], $wgHooks[$name] );
109 }
110 }
111
112 /**
113 * @param string $event Event name
114 * @param array|callable $hook
115 * @param array $args Array of parameters passed to hook functions
116 * @param string|null $deprecatedVersion [optional]
117 * @param string &$fname [optional] Readable name of hook [returned]
118 * @return null|string|bool
119 */
120 private static function callHook( $event, $hook, array $args, $deprecatedVersion = null,
121 &$fname = null
122 ) {
123 // Turn non-array values into an array. (Can't use casting because of objects.)
124 if ( !is_array( $hook ) ) {
125 $hook = [ $hook ];
126 }
127
128 if ( !array_filter( $hook ) ) {
129 // Either array is empty or it's an array filled with null/false/empty.
130 return null;
131 }
132
133 if ( is_array( $hook[0] ) ) {
134 // First element is an array, meaning the developer intended
135 // the first element to be a callback. Merge it in so that
136 // processing can be uniform.
137 $hook = array_merge( $hook[0], array_slice( $hook, 1 ) );
138 }
139
140 /**
141 * $hook can be: a function, an object, an array of $function and
142 * $data, an array of just a function, an array of object and
143 * method, or an array of object, method, and data.
144 */
145 if ( $hook[0] instanceof Closure ) {
146 $fname = "hook-$event-closure";
147 $callback = array_shift( $hook );
148 } elseif ( is_object( $hook[0] ) ) {
149 $object = array_shift( $hook );
150 $method = array_shift( $hook );
151
152 // If no method was specified, default to on$event.
153 if ( $method === null ) {
154 $method = "on$event";
155 }
156
157 $fname = get_class( $object ) . '::' . $method;
158 $callback = [ $object, $method ];
159 } elseif ( is_string( $hook[0] ) ) {
160 $fname = $callback = array_shift( $hook );
161 } else {
162 throw new MWException( 'Unknown datatype in hooks for ' . $event . "\n" );
163 }
164
165 // Run autoloader (workaround for call_user_func_array bug)
166 // and throw error if not callable.
167 if ( !is_callable( $callback ) ) {
168 throw new MWException( 'Invalid callback ' . $fname . ' in hooks for ' . $event . "\n" );
169 }
170
171 // mark hook as deprecated, if deprecation version is specified
172 if ( $deprecatedVersion !== null ) {
173 wfDeprecated( "$event hook (used in $fname)", $deprecatedVersion );
174 }
175
176 // Call the hook.
177 $hook_args = array_merge( $hook, $args );
178 return call_user_func_array( $callback, $hook_args );
179 }
180
181 /**
182 * Call hook functions defined in Hooks::register and $wgHooks.
183 *
184 * For the given hook event, fetch the array of hook events and
185 * process them. Determine the proper callback for each hook and
186 * then call the actual hook using the appropriate arguments.
187 * Finally, process the return value and return/throw accordingly.
188 *
189 * For hook event that are not abortable through a handler's return value,
190 * use runWithoutAbort() instead.
191 *
192 * @param string $event Event name
193 * @param array $args Array of parameters passed to hook functions
194 * @param string|null $deprecatedVersion [optional] Mark hook as deprecated with version number
195 * @return bool True if no handler aborted the hook
196 *
197 * @throws Exception
198 * @throws FatalError
199 * @throws MWException
200 * @since 1.22 A hook function is not required to return a value for
201 * processing to continue. Not returning a value (or explicitly
202 * returning null) is equivalent to returning true.
203 */
204 public static function run( $event, array $args = [], $deprecatedVersion = null ) {
205 foreach ( self::getHandlers( $event ) as $hook ) {
206 $retval = self::callHook( $event, $hook, $args, $deprecatedVersion );
207 if ( $retval === null ) {
208 continue;
209 }
210
211 // Process the return value.
212 if ( is_string( $retval ) ) {
213 // String returned means error.
214 throw new FatalError( $retval );
215 } elseif ( $retval === false ) {
216 // False was returned. Stop processing, but no error.
217 return false;
218 }
219 }
220
221 return true;
222 }
223
224 /**
225 * Call hook functions defined in Hooks::register and $wgHooks.
226 *
227 * @param string $event Event name
228 * @param array $args Array of parameters passed to hook functions
229 * @param string|null $deprecatedVersion [optional] Mark hook as deprecated with version number
230 * @return bool Always true
231 * @throws MWException If a callback is invalid, unknown
232 * @throws UnexpectedValueException If a callback returns an abort value.
233 * @since 1.30
234 */
235 public static function runWithoutAbort( $event, array $args = [], $deprecatedVersion = null ) {
236 foreach ( self::getHandlers( $event ) as $hook ) {
237 $fname = null;
238 $retval = self::callHook( $event, $hook, $args, $deprecatedVersion, $fname );
239 if ( $retval !== null && $retval !== true ) {
240 throw new UnexpectedValueException( "Invalid return from $fname for unabortable $event." );
241 }
242 }
243 return true;
244 }
245 }