[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> class-wp-hook.php (source)

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


Generated: Sun Apr 18 01:00:12 2021 Cross-referenced by PHPXref 0.7.1