暂无描述

class-wp-hook.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. /**
  3. * Plugin API: WP_Hook class
  4. *
  5. * @package WordPress
  6. * @subpackage Plugin
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core class used to implement action and filter hook functionality.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see Iterator
  15. * @see ArrayAccess
  16. */
  17. final class WP_Hook implements Iterator, ArrayAccess {
  18. /**
  19. * Hook callbacks.
  20. *
  21. * @since 4.7.0
  22. * @var array
  23. */
  24. public $callbacks = array();
  25. /**
  26. * The priority keys of actively running iterations of a hook.
  27. *
  28. * @since 4.7.0
  29. * @var array
  30. */
  31. private $iterations = array();
  32. /**
  33. * The current priority of actively running iterations of a hook.
  34. *
  35. * @since 4.7.0
  36. * @var array
  37. */
  38. private $current_priority = array();
  39. /**
  40. * Number of levels this hook can be recursively called.
  41. *
  42. * @since 4.7.0
  43. * @var int
  44. */
  45. private $nesting_level = 0;
  46. /**
  47. * Flag for if we're currently doing an action, rather than a filter.
  48. *
  49. * @since 4.7.0
  50. * @var bool
  51. */
  52. private $doing_action = false;
  53. /**
  54. * Adds a callback function to a filter hook.
  55. *
  56. * @since 4.7.0
  57. *
  58. * @param string $hook_name The name of the filter to add the callback to.
  59. * @param callable $callback The callback to be run when the filter is applied.
  60. * @param int $priority The order in which the functions associated with a particular filter
  61. * are executed. Lower numbers correspond with earlier execution,
  62. * and functions with the same priority are executed in the order
  63. * in which they were added to the filter.
  64. * @param int $accepted_args The number of arguments the function accepts.
  65. */
  66. public function add_filter( $hook_name, $callback, $priority, $accepted_args ) {
  67. $idx = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
  68. $priority_existed = isset( $this->callbacks[ $priority ] );
  69. $this->callbacks[ $priority ][ $idx ] = array(
  70. 'function' => $callback,
  71. 'accepted_args' => $accepted_args,
  72. );
  73. // If we're adding a new priority to the list, put them back in sorted order.
  74. if ( ! $priority_existed && count( $this->callbacks ) > 1 ) {
  75. ksort( $this->callbacks, SORT_NUMERIC );
  76. }
  77. if ( $this->nesting_level > 0 ) {
  78. $this->resort_active_iterations( $priority, $priority_existed );
  79. }
  80. }
  81. /**
  82. * Handles resetting callback priority keys mid-iteration.
  83. *
  84. * @since 4.7.0
  85. *
  86. * @param false|int $new_priority Optional. The priority of the new filter being added. Default false,
  87. * for no priority being added.
  88. * @param bool $priority_existed Optional. Flag for whether the priority already existed before the new
  89. * filter was added. Default false.
  90. */
  91. private function resort_active_iterations( $new_priority = false, $priority_existed = false ) {
  92. $new_priorities = array_keys( $this->callbacks );
  93. // If there are no remaining hooks, clear out all running iterations.
  94. if ( ! $new_priorities ) {
  95. foreach ( $this->iterations as $index => $iteration ) {
  96. $this->iterations[ $index ] = $new_priorities;
  97. }
  98. return;
  99. }
  100. $min = min( $new_priorities );
  101. foreach ( $this->iterations as $index => &$iteration ) {
  102. $current = current( $iteration );
  103. // If we're already at the end of this iteration, just leave the array pointer where it is.
  104. if ( false === $current ) {
  105. continue;
  106. }
  107. $iteration = $new_priorities;
  108. if ( $current < $min ) {
  109. array_unshift( $iteration, $current );
  110. continue;
  111. }
  112. while ( current( $iteration ) < $current ) {
  113. if ( false === next( $iteration ) ) {
  114. break;
  115. }
  116. }
  117. // If we have a new priority that didn't exist, but ::apply_filters() or ::do_action() thinks it's the current priority...
  118. if ( $new_priority === $this->current_priority[ $index ] && ! $priority_existed ) {
  119. /*
  120. * ...and the new priority is the same as what $this->iterations thinks is the previous
  121. * priority, we need to move back to it.
  122. */
  123. if ( false === current( $iteration ) ) {
  124. // If we've already moved off the end of the array, go back to the last element.
  125. $prev = end( $iteration );
  126. } else {
  127. // Otherwise, just go back to the previous element.
  128. $prev = prev( $iteration );
  129. }
  130. if ( false === $prev ) {
  131. // Start of the array. Reset, and go about our day.
  132. reset( $iteration );
  133. } elseif ( $new_priority !== $prev ) {
  134. // Previous wasn't the same. Move forward again.
  135. next( $iteration );
  136. }
  137. }
  138. }
  139. unset( $iteration );
  140. }
  141. /**
  142. * Removes a callback function from a filter hook.
  143. *
  144. * @since 4.7.0
  145. *
  146. * @param string $hook_name The filter hook to which the function to be removed is hooked.
  147. * @param callable|string|array $callback The callback to be removed from running when the filter is applied.
  148. * This method can be called unconditionally to speculatively remove
  149. * a callback that may or may not exist.
  150. * @param int $priority The exact priority used when adding the original filter callback.
  151. * @return bool Whether the callback existed before it was removed.
  152. */
  153. public function remove_filter( $hook_name, $callback, $priority ) {
  154. $function_key = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
  155. $exists = isset( $this->callbacks[ $priority ][ $function_key ] );
  156. if ( $exists ) {
  157. unset( $this->callbacks[ $priority ][ $function_key ] );
  158. if ( ! $this->callbacks[ $priority ] ) {
  159. unset( $this->callbacks[ $priority ] );
  160. if ( $this->nesting_level > 0 ) {
  161. $this->resort_active_iterations();
  162. }
  163. }
  164. }
  165. return $exists;
  166. }
  167. /**
  168. * Checks if a specific callback has been registered for this hook.
  169. *
  170. * When using the `$callback` argument, this function may return a non-boolean value
  171. * that evaluates to false (e.g. 0), so use the `===` operator for testing the return value.
  172. *
  173. * @since 4.7.0
  174. *
  175. * @param string $hook_name Optional. The name of the filter hook. Default empty.
  176. * @param callable|string|array|false $callback Optional. The callback to check for.
  177. * This method can be called unconditionally to speculatively check
  178. * a callback that may or may not exist. Default false.
  179. * @return bool|int If `$callback` is omitted, returns boolean for whether the hook has
  180. * anything registered. When checking a specific function, the priority
  181. * of that hook is returned, or false if the function is not attached.
  182. */
  183. public function has_filter( $hook_name = '', $callback = false ) {
  184. if ( false === $callback ) {
  185. return $this->has_filters();
  186. }
  187. $function_key = _wp_filter_build_unique_id( $hook_name, $callback, false );
  188. if ( ! $function_key ) {
  189. return false;
  190. }
  191. foreach ( $this->callbacks as $priority => $callbacks ) {
  192. if ( isset( $callbacks[ $function_key ] ) ) {
  193. return $priority;
  194. }
  195. }
  196. return false;
  197. }
  198. /**
  199. * Checks if any callbacks have been registered for this hook.
  200. *
  201. * @since 4.7.0
  202. *
  203. * @return bool True if callbacks have been registered for the current hook, otherwise false.
  204. */
  205. public function has_filters() {
  206. foreach ( $this->callbacks as $callbacks ) {
  207. if ( $callbacks ) {
  208. return true;
  209. }
  210. }
  211. return false;
  212. }
  213. /**
  214. * Removes all callbacks from the current filter.
  215. *
  216. * @since 4.7.0
  217. *
  218. * @param int|false $priority Optional. The priority number to remove. Default false.
  219. */
  220. public function remove_all_filters( $priority = false ) {
  221. if ( ! $this->callbacks ) {
  222. return;
  223. }
  224. if ( false === $priority ) {
  225. $this->callbacks = array();
  226. } elseif ( isset( $this->callbacks[ $priority ] ) ) {
  227. unset( $this->callbacks[ $priority ] );
  228. }
  229. if ( $this->nesting_level > 0 ) {
  230. $this->resort_active_iterations();
  231. }
  232. }
  233. /**
  234. * Calls the callback functions that have been added to a filter hook.
  235. *
  236. * @since 4.7.0
  237. *
  238. * @param mixed $value The value to filter.
  239. * @param array $args Additional parameters to pass to the callback functions.
  240. * This array is expected to include $value at index 0.
  241. * @return mixed The filtered value after all hooked functions are applied to it.
  242. */
  243. public function apply_filters( $value, $args ) {
  244. if ( ! $this->callbacks ) {
  245. return $value;
  246. }
  247. $nesting_level = $this->nesting_level++;
  248. $this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
  249. $num_args = count( $args );
  250. do {
  251. $this->current_priority[ $nesting_level ] = current( $this->iterations[ $nesting_level ] );
  252. $priority = $this->current_priority[ $nesting_level ];
  253. foreach ( $this->callbacks[ $priority ] as $the_ ) {
  254. if ( ! $this->doing_action ) {
  255. $args[0] = $value;
  256. }
  257. // Avoid the array_slice() if possible.
  258. if ( 0 == $the_['accepted_args'] ) {
  259. $value = call_user_func( $the_['function'] );
  260. } elseif ( $the_['accepted_args'] >= $num_args ) {
  261. $value = call_user_func_array( $the_['function'], $args );
  262. } else {
  263. $value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
  264. }
  265. }
  266. } while ( false !== next( $this->iterations[ $nesting_level ] ) );
  267. unset( $this->iterations[ $nesting_level ] );
  268. unset( $this->current_priority[ $nesting_level ] );
  269. $this->nesting_level--;
  270. return $value;
  271. }
  272. /**
  273. * Calls the callback functions that have been added to an action hook.
  274. *
  275. * @since 4.7.0
  276. *
  277. * @param array $args Parameters to pass to the callback functions.
  278. */
  279. public function do_action( $args ) {
  280. $this->doing_action = true;
  281. $this->apply_filters( '', $args );
  282. // If there are recursive calls to the current action, we haven't finished it until we get to the last one.
  283. if ( ! $this->nesting_level ) {
  284. $this->doing_action = false;
  285. }
  286. }
  287. /**
  288. * Processes the functions hooked into the 'all' hook.
  289. *
  290. * @since 4.7.0
  291. *
  292. * @param array $args Arguments to pass to the hook callbacks. Passed by reference.
  293. */
  294. public function do_all_hook( &$args ) {
  295. $nesting_level = $this->nesting_level++;
  296. $this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
  297. do {
  298. $priority = current( $this->iterations[ $nesting_level ] );
  299. foreach ( $this->callbacks[ $priority ] as $the_ ) {
  300. call_user_func_array( $the_['function'], $args );
  301. }
  302. } while ( false !== next( $this->iterations[ $nesting_level ] ) );
  303. unset( $this->iterations[ $nesting_level ] );
  304. $this->nesting_level--;
  305. }
  306. /**
  307. * Return the current priority level of the currently running iteration of the hook.
  308. *
  309. * @since 4.7.0
  310. *
  311. * @return int|false If the hook is running, return the current priority level.
  312. * If it isn't running, return false.
  313. */
  314. public function current_priority() {
  315. if ( false === current( $this->iterations ) ) {
  316. return false;
  317. }
  318. return current( current( $this->iterations ) );
  319. }
  320. /**
  321. * Normalizes filters set up before WordPress has initialized to WP_Hook objects.
  322. *
  323. * The `$filters` parameter should be an array keyed by hook name, with values
  324. * containing either:
  325. *
  326. * - A `WP_Hook` instance
  327. * - An array of callbacks keyed by their priorities
  328. *
  329. * Examples:
  330. *
  331. * $filters = array(
  332. * 'wp_fatal_error_handler_enabled' => array(
  333. * 10 => array(
  334. * array(
  335. * 'accepted_args' => 0,
  336. * 'function' => function() {
  337. * return false;
  338. * },
  339. * ),
  340. * ),
  341. * ),
  342. * );
  343. *
  344. * @since 4.7.0
  345. *
  346. * @param array $filters Filters to normalize. See documentation above for details.
  347. * @return WP_Hook[] Array of normalized filters.
  348. */
  349. public static function build_preinitialized_hooks( $filters ) {
  350. /** @var WP_Hook[] $normalized */
  351. $normalized = array();
  352. foreach ( $filters as $hook_name => $callback_groups ) {
  353. if ( is_object( $callback_groups ) && $callback_groups instanceof WP_Hook ) {
  354. $normalized[ $hook_name ] = $callback_groups;
  355. continue;
  356. }
  357. $hook = new WP_Hook();
  358. // Loop through callback groups.
  359. foreach ( $callback_groups as $priority => $callbacks ) {
  360. // Loop through callbacks.
  361. foreach ( $callbacks as $cb ) {
  362. $hook->add_filter( $hook_name, $cb['function'], $priority, $cb['accepted_args'] );
  363. }
  364. }
  365. $normalized[ $hook_name ] = $hook;
  366. }
  367. return $normalized;
  368. }
  369. /**
  370. * Determines whether an offset value exists.
  371. *
  372. * @since 4.7.0
  373. *
  374. * @link https://www.php.net/manual/en/arrayaccess.offsetexists.php
  375. *
  376. * @param mixed $offset An offset to check for.
  377. * @return bool True if the offset exists, false otherwise.
  378. */
  379. #[ReturnTypeWillChange]
  380. public function offsetExists( $offset ) {
  381. return isset( $this->callbacks[ $offset ] );
  382. }
  383. /**
  384. * Retrieves a value at a specified offset.
  385. *
  386. * @since 4.7.0
  387. *
  388. * @link https://www.php.net/manual/en/arrayaccess.offsetget.php
  389. *
  390. * @param mixed $offset The offset to retrieve.
  391. * @return mixed If set, the value at the specified offset, null otherwise.
  392. */
  393. #[ReturnTypeWillChange]
  394. public function offsetGet( $offset ) {
  395. return isset( $this->callbacks[ $offset ] ) ? $this->callbacks[ $offset ] : null;
  396. }
  397. /**
  398. * Sets a value at a specified offset.
  399. *
  400. * @since 4.7.0
  401. *
  402. * @link https://www.php.net/manual/en/arrayaccess.offsetset.php
  403. *
  404. * @param mixed $offset The offset to assign the value to.
  405. * @param mixed $value The value to set.
  406. */
  407. #[ReturnTypeWillChange]
  408. public function offsetSet( $offset, $value ) {
  409. if ( is_null( $offset ) ) {
  410. $this->callbacks[] = $value;
  411. } else {
  412. $this->callbacks[ $offset ] = $value;
  413. }
  414. }
  415. /**
  416. * Unsets a specified offset.
  417. *
  418. * @since 4.7.0
  419. *
  420. * @link https://www.php.net/manual/en/arrayaccess.offsetunset.php
  421. *
  422. * @param mixed $offset The offset to unset.
  423. */
  424. #[ReturnTypeWillChange]
  425. public function offsetUnset( $offset ) {
  426. unset( $this->callbacks[ $offset ] );
  427. }
  428. /**
  429. * Returns the current element.
  430. *
  431. * @since 4.7.0
  432. *
  433. * @link https://www.php.net/manual/en/iterator.current.php
  434. *
  435. * @return array Of callbacks at current priority.
  436. */
  437. #[ReturnTypeWillChange]
  438. public function current() {
  439. return current( $this->callbacks );
  440. }
  441. /**
  442. * Moves forward to the next element.
  443. *
  444. * @since 4.7.0
  445. *
  446. * @link https://www.php.net/manual/en/iterator.next.php
  447. *
  448. * @return array Of callbacks at next priority.
  449. */
  450. #[ReturnTypeWillChange]
  451. public function next() {
  452. return next( $this->callbacks );
  453. }
  454. /**
  455. * Returns the key of the current element.
  456. *
  457. * @since 4.7.0
  458. *
  459. * @link https://www.php.net/manual/en/iterator.key.php
  460. *
  461. * @return mixed Returns current priority on success, or NULL on failure
  462. */
  463. #[ReturnTypeWillChange]
  464. public function key() {
  465. return key( $this->callbacks );
  466. }
  467. /**
  468. * Checks if current position is valid.
  469. *
  470. * @since 4.7.0
  471. *
  472. * @link https://www.php.net/manual/en/iterator.valid.php
  473. *
  474. * @return bool Whether the current position is valid.
  475. */
  476. #[ReturnTypeWillChange]
  477. public function valid() {
  478. return key( $this->callbacks ) !== null;
  479. }
  480. /**
  481. * Rewinds the Iterator to the first element.
  482. *
  483. * @since 4.7.0
  484. *
  485. * @link https://www.php.net/manual/en/iterator.rewind.php
  486. */
  487. #[ReturnTypeWillChange]
  488. public function rewind() {
  489. reset( $this->callbacks );
  490. }
  491. }