[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/abilities-api/ -> class-wp-abilities-registry.php (source)

   1  <?php
   2  /**
   3   * Abilities API
   4   *
   5   * Defines WP_Abilities_Registry class.
   6   *
   7   * @package WordPress
   8   * @subpackage Abilities API
   9   * @since 6.9.0
  10   */
  11  
  12  declare( strict_types = 1 );
  13  
  14  /**
  15   * Manages the registration and lookup of abilities.
  16   *
  17   * @since 6.9.0
  18   * @access private
  19   */
  20  final class WP_Abilities_Registry {
  21      /**
  22       * The singleton instance of the registry.
  23       *
  24       * @since 6.9.0
  25       * @var self|null
  26       */
  27      private static $instance = null;
  28  
  29      /**
  30       * Holds the registered abilities.
  31       *
  32       * @since 6.9.0
  33       * @var WP_Ability[]
  34       */
  35      private $registered_abilities = array();
  36  
  37      /**
  38       * Registers a new ability.
  39       *
  40       * Do not use this method directly. Instead, use the `wp_register_ability()` function.
  41       *
  42       * @since 6.9.0
  43       * @since 7.1.0 Added the `public` meta argument.
  44       * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`.
  45       *
  46       * @see wp_register_ability()
  47       *
  48       * @param string               $name The name of the ability. The name must be a string containing a namespace
  49       *                                   prefix, i.e. `my-plugin/my-ability`. It can only contain lowercase
  50       *                                   alphanumeric characters, dashes and the forward slash.
  51       * @param array<string, mixed> $args {
  52       *     An associative array of arguments for the ability.
  53       *
  54       *     @type string               $label                 The human-readable label for the ability.
  55       *     @type string               $description           A detailed description of what the ability does.
  56       *     @type string               $category              Optional. The ability category slug this ability belongs to.
  57       *                                                       Defaults to `uncategorized`.
  58       *     @type callable             $execute_callback      A callback function to execute when the ability is invoked.
  59       *                                                       Receives optional mixed input and returns mixed result or WP_Error.
  60       *     @type callable             $permission_callback   A callback function to check permissions before execution.
  61       *                                                       Receives optional mixed input and returns bool or WP_Error.
  62       *     @type array<string, mixed> $input_schema          Optional. JSON Schema definition for the ability's input.
  63       *     @type array<string, mixed> $output_schema         Optional. JSON Schema definition for the ability's output.
  64       *     @type array<string, mixed> $meta                  {
  65       *         Optional. Additional metadata for the ability.
  66       *
  67       *         @type array<string, bool|null> $annotations  {
  68       *             Optional. Semantic annotations describing the ability's behavioral characteristics.
  69       *             These annotations are hints for tooling and documentation.
  70       *
  71       *             @type bool|null $readonly    Optional. If true, the ability does not modify its environment.
  72       *             @type bool|null $destructive Optional. If true, the ability may perform destructive updates to its environment.
  73       *                                          If false, the ability performs only additive updates.
  74       *             @type bool|null $idempotent  Optional. If true, calling the ability repeatedly with the same arguments
  75       *                                          will have no additional effect on its environment.
  76       *         }
  77       *         @type bool                     $public       Optional. Whether the ability is meant to be available
  78       *                                                      to clients such as the REST API, MCP, or AI agents.
  79       *                                                      Seeds the default for per-channel flags like
  80       *                                                      `$show_in_rest`. Defaults to false.
  81       *         @type bool                     $show_in_rest Optional. Whether to expose this ability in the REST API.
  82       *                                                      Default is the value of `$public` when set, false otherwise.
  83       *     }
  84       *     @type string               $ability_class         Optional. Custom class to instantiate instead of WP_Ability.
  85       * }
  86       * @return WP_Ability|null The registered ability instance on success, null on failure.
  87       */
  88  	public function register( string $name, array $args ): ?WP_Ability {
  89          if ( ! preg_match( '/^[a-z0-9-]+\/[a-z0-9-]+$/', $name ) ) {
  90              _doing_it_wrong(
  91                  __METHOD__,
  92                  __(
  93                      'Ability name must be a string containing a namespace prefix, i.e. "my-plugin/my-ability". It can only contain lowercase alphanumeric characters, dashes and the forward slash.'
  94                  ),
  95                  '6.9.0'
  96              );
  97              return null;
  98          }
  99  
 100          if ( $this->is_registered( $name ) ) {
 101              _doing_it_wrong(
 102                  __METHOD__,
 103                  /* translators: %s: Ability name. */
 104                  sprintf( __( 'Ability "%s" is already registered.' ), esc_html( $name ) ),
 105                  '6.9.0'
 106              );
 107              return null;
 108          }
 109  
 110          /**
 111           * Filters the ability arguments before they are validated and used to instantiate the ability.
 112           *
 113           * @since 6.9.0
 114           * @since 7.1.0 Added the `public` meta argument.
 115           * @since 7.2.0 The `category` argument is now optional and defaults to `uncategorized`.
 116           *
 117           * @param array<string, mixed> $args {
 118           *     An associative array of arguments for the ability.
 119           *
 120           *     @type string               $label                 The human-readable label for the ability.
 121           *     @type string               $description           A detailed description of what the ability does.
 122           *     @type string               $category              Optional. The ability category slug this ability belongs to.
 123           *                                                       Defaults to `uncategorized`.
 124           *     @type callable             $execute_callback      A callback function to execute when the ability is invoked.
 125           *                                                       Receives optional mixed input and returns mixed result or WP_Error.
 126           *     @type callable             $permission_callback   A callback function to check permissions before execution.
 127           *                                                       Receives optional mixed input and returns bool or WP_Error.
 128           *     @type array<string, mixed> $input_schema          Optional. JSON Schema definition for the ability's input.
 129           *     @type array<string, mixed> $output_schema         Optional. JSON Schema definition for the ability's output.
 130           *     @type array<string, mixed> $meta                  {
 131           *         Optional. Additional metadata for the ability.
 132           *
 133           *         @type array<string, bool|string> $annotations  Optional. Annotation metadata for the ability.
 134           *         @type bool                       $public       Optional. Whether the ability is meant to be
 135           *                                                        available to clients such as the REST API, MCP, or AI
 136           *                                                        agents. Seeds the default for per-channel flags like
 137           *                                                        `$show_in_rest`. Defaults to false.
 138           *         @type bool                       $show_in_rest Optional. Whether to expose this ability in the REST API.
 139           *                                                        Default is the value of `$public` when set, false otherwise.
 140           *     }
 141           *     @type string               $ability_class         Optional. Custom class to instantiate instead of WP_Ability.
 142           * }
 143           * @param string               $name The name of the ability, with its namespace.
 144           */
 145          $args = apply_filters( 'wp_register_ability_args', $args, $name );
 146  
 147          if ( ! array_key_exists( 'category', $args ) ) {
 148              $args['category'] = 'uncategorized';
 149          }
 150  
 151          if ( ! is_string( $args['category'] ) ) {
 152              _doing_it_wrong(
 153                  __METHOD__,
 154                  __( 'Ability category must be a string.' ),
 155                  '6.9.0'
 156              );
 157              return null;
 158          }
 159  
 160          if ( ! wp_has_ability_category( $args['category'] ) ) {
 161              _doing_it_wrong(
 162                  __METHOD__,
 163                  sprintf(
 164                      /* translators: %1$s: ability category slug, %2$s: ability name */
 165                      __( 'Ability category "%1$s" is not registered. Please register the ability category before assigning it to ability "%2$s".' ),
 166                      esc_html( $args['category'] ),
 167                      esc_html( $name )
 168                  ),
 169                  '6.9.0'
 170              );
 171              return null;
 172          }
 173  
 174          // The class is only used to instantiate the ability, and is not a property of the ability itself.
 175          if ( isset( $args['ability_class'] ) && ! is_a( $args['ability_class'], WP_Ability::class, true ) ) {
 176              _doing_it_wrong(
 177                  __METHOD__,
 178                  __( 'The ability args should provide a valid `ability_class` that extends WP_Ability.' ),
 179                  '6.9.0'
 180              );
 181              return null;
 182          }
 183  
 184          /** @var class-string<WP_Ability> */
 185          $ability_class = $args['ability_class'] ?? WP_Ability::class;
 186          unset( $args['ability_class'] );
 187  
 188          try {
 189              // WP_Ability::prepare_properties() will throw an exception if the properties are invalid.
 190              $ability = new $ability_class( $name, $args );
 191          } catch ( InvalidArgumentException $e ) {
 192              _doing_it_wrong(
 193                  __METHOD__,
 194                  $e->getMessage(),
 195                  '6.9.0'
 196              );
 197              return null;
 198          }
 199  
 200          $this->registered_abilities[ $name ] = $ability;
 201          return $ability;
 202      }
 203  
 204      /**
 205       * Unregisters an ability.
 206       *
 207       * Do not use this method directly. Instead, use the `wp_unregister_ability()` function.
 208       *
 209       * @since 6.9.0
 210       *
 211       * @see wp_unregister_ability()
 212       *
 213       * @param string $name The name of the registered ability, with its namespace.
 214       * @return WP_Ability|null The unregistered ability instance on success, null on failure.
 215       */
 216  	public function unregister( string $name ): ?WP_Ability {
 217          if ( ! $this->is_registered( $name ) ) {
 218              _doing_it_wrong(
 219                  __METHOD__,
 220                  /* translators: %s: Ability name. */
 221                  sprintf( __( 'Ability "%s" not found.' ), esc_html( $name ) ),
 222                  '6.9.0'
 223              );
 224              return null;
 225          }
 226  
 227          $unregistered_ability = $this->registered_abilities[ $name ];
 228          unset( $this->registered_abilities[ $name ] );
 229  
 230          return $unregistered_ability;
 231      }
 232  
 233      /**
 234       * Retrieves the list of all registered abilities.
 235       *
 236       * Do not use this method directly. Instead, use the `wp_get_abilities()` function.
 237       *
 238       * @since 6.9.0
 239       *
 240       * @see wp_get_abilities()
 241       *
 242       * @return WP_Ability[] The array of registered abilities.
 243       */
 244  	public function get_all_registered(): array {
 245          return $this->registered_abilities;
 246      }
 247  
 248      /**
 249       * Checks if an ability is registered.
 250       *
 251       * Do not use this method directly. Instead, use the `wp_has_ability()` function.
 252       *
 253       * @since 6.9.0
 254       *
 255       * @see wp_has_ability()
 256       *
 257       * @param string $name The name of the registered ability, with its namespace.
 258       * @return bool True if the ability is registered, false otherwise.
 259       */
 260  	public function is_registered( string $name ): bool {
 261          return isset( $this->registered_abilities[ $name ] );
 262      }
 263  
 264      /**
 265       * Retrieves a registered ability.
 266       *
 267       * Do not use this method directly. Instead, use the `wp_get_ability()` function.
 268       *
 269       * @since 6.9.0
 270       *
 271       * @see wp_get_ability()
 272       *
 273       * @param string $name The name of the registered ability, with its namespace.
 274       * @return WP_Ability|null The registered ability instance, or null if it is not registered.
 275       */
 276  	public function get_registered( string $name ): ?WP_Ability {
 277          if ( ! $this->is_registered( $name ) ) {
 278              _doing_it_wrong(
 279                  __METHOD__,
 280                  /* translators: %s: Ability name. */
 281                  sprintf( __( 'Ability "%s" not found.' ), esc_html( $name ) ),
 282                  '6.9.0'
 283              );
 284              return null;
 285          }
 286          return $this->registered_abilities[ $name ];
 287      }
 288  
 289      /**
 290       * Utility method to retrieve the main instance of the registry class.
 291       *
 292       * The instance will be created if it does not exist yet.
 293       *
 294       * @since 6.9.0
 295       *
 296       * @return WP_Abilities_Registry|null The main registry instance, or null when `init` action has not fired.
 297       */
 298  	public static function get_instance(): ?self {
 299          if ( ! did_action( 'init' ) ) {
 300              _doing_it_wrong(
 301                  __METHOD__,
 302                  sprintf(
 303                      // translators: %s: init action.
 304                      __( 'Ability API should not be initialized before the %s action has fired.' ),
 305                      '<code>init</code>'
 306                  ),
 307                  '6.9.0'
 308              );
 309              return null;
 310          }
 311  
 312          if ( null === self::$instance ) {
 313              self::$instance = new self();
 314  
 315              // Ensure ability category registry is initialized first to allow categories to be registered
 316              // before abilities that depend on them.
 317              WP_Ability_Categories_Registry::get_instance();
 318  
 319              /**
 320               * Fires when preparing abilities registry.
 321               *
 322               * Abilities should be created and register their hooks on this action rather
 323               * than another action to ensure they're only loaded when needed.
 324               *
 325               * @since 6.9.0
 326               *
 327               * @param WP_Abilities_Registry $instance Abilities registry object.
 328               */
 329              do_action( 'wp_abilities_api_init', self::$instance );
 330          }
 331  
 332          return self::$instance;
 333      }
 334  
 335      /**
 336       * Wakeup magic method.
 337       *
 338       * @since 6.9.0
 339       * @throws LogicException If the registry object is unserialized.
 340       *                        This is a security hardening measure to prevent unserialization of the registry.
 341       */
 342  	public function __wakeup(): void {
 343          throw new LogicException( __CLASS__ . ' should never be unserialized.' );
 344      }
 345  
 346      /**
 347       * Sleep magic method.
 348       *
 349       * @since 6.9.0
 350       * @throws LogicException If the registry object is serialized.
 351       *                        This is a security hardening measure to prevent serialization of the registry.
 352       */
 353  	public function __sleep(): array {
 354          throw new LogicException( __CLASS__ . ' should never be serialized.' );
 355      }
 356  }


Generated : Fri Sep 4 08:20:24 2026 Cross-referenced by PHPXref