From 3c8259c0de580ce1ce5b3bbc6f2f789f81cb0a93 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:25:45 -0600 Subject: [PATCH 01/14] Add the core/settings-get ability from Core --- src/Settings/Settings_Get.php | 360 ++++++++++++++++++++++++++++++++++ 1 file changed, 360 insertions(+) create mode 100644 src/Settings/Settings_Get.php diff --git a/src/Settings/Settings_Get.php b/src/Settings/Settings_Get.php new file mode 100644 index 0000000..bb99a7c --- /dev/null +++ b/src/Settings/Settings_Get.php @@ -0,0 +1,360 @@ +}> + */ + private $exposed_settings = array(); + + /** + * The canonical ability name. + * + * @return string The ability name. + */ + protected function ability_name(): string { + return 'core/settings-get'; + } + + /** + * The ability label, as registered in core. + * + * @return string The ability label. + */ + protected function label(): string { + return __( 'Get Settings' ); + } + + /** + * The ability description, as registered in core. + * + * @return string The ability description. + */ + protected function description(): string { + return __( 'Returns WordPress settings as a flat map of setting name to value. By default returns all settings exposed to abilities, or optionally a subset filtered by settings group, by setting name, or both. A setting whose value does not match its schema is left out. Requires an authenticated user who can manage options.' ); + } + + /** + * The ability category, as registered in core. + * + * @return string The category slug. + */ + protected function category_slug(): string { + return self::CATEGORY; + } + + /** + * The input JSON Schema, as core builds it when registering. + * + * @return array The input JSON Schema. + */ + protected function input_schema(): array { + $groups = array_values( array_unique( array_filter( array_column( $this->exposed_settings, 'group' ) ) ) ); + + return $this->get_settings_get_input_schema( $groups, array_map( 'strval', array_keys( $this->exposed_settings ) ) ); + } + + /** + * The output JSON Schema, as core builds it when registering. + * + * @return array The output JSON Schema. + */ + protected function output_schema(): array { + return $this->get_settings_get_output_schema(); + } + + /** + * The execute callback, as registered in core. + * + * @return callable(mixed): array The execute callback. + */ + protected function make_execute_callback(): callable { + return function ( $input = array() ): array { + return $this->execute_settings_get( $input ); + }; + } + + /** + * No permission callback, as registered in core. + * + * The `manage_options` floor from required_capabilities() owns authorization. + * + * @return null No permission callback. + */ + protected function make_permission_callback(): ?callable { + return null; + } + + /** + * The authored ability meta, exactly as core registers it. + * + * @return array The ability meta. + */ + protected function ability_meta(): array { + return array( + 'annotations' => array( + 'readonly' => true, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ); + } + + /** + * The request-level capability floor, as registered in core. + * + * @return list The required capabilities. + */ + protected function required_capabilities(): array { + return array( 'manage_options' ); + } + + /** + * Takes the exposed-settings snapshot, as core's register() does before registering. + */ + protected function prepare(): void { + $this->exposed_settings = $this->get_exposed_settings(); + } + + /** + * Whether any setting is exposed, as core's register() checks before registering. + * + * @return bool True when at least one setting is exposed. + */ + public function should_register(): bool { + return ! empty( $this->exposed_settings ); + } + + /** + * Executes the `core/settings-get` ability. + * + * @since x.x.x + * + * @param mixed $input Optional. The ability input. Default empty array. + * @return array Map of exposed setting name to current value. + */ + private function execute_settings_get( $input = array() ): array { + $input = rest_sanitize_object( $input ); + $group = isset( $input['group'] ) && is_string( $input['group'] ) ? $input['group'] : ''; + $fields = rest_sanitize_array( $input['fields'] ?? array() ); + + $result = array(); + foreach ( $this->exposed_settings as $exposed_name => $setting ) { + if ( '' !== $group && $setting['group'] !== $group ) { + continue; + } + if ( ! empty( $fields ) && ! in_array( (string) $exposed_name, $fields, true ) ) { + continue; + } + + /* + * As the settings endpoint does, read a setting that was never saved as its registered + * default, or leave it out when it has none: get_option() would return false, which a + * boolean schema accepts as a value and an array schema reads as an empty list. + */ + $value = get_option( $setting['option'], $setting['default'] ); + if ( null === $value ) { + continue; + } + + // WordPress stores false as '', which the boolean schema rejects. + if ( '' === $value && 'boolean' === $setting['schema']['type'] ) { + $value = false; + } + + /* + * Leave out a value its schema rejects, before sanitizing (which could make it pass) or + * after (which could make it fail), instead of failing output validation for every setting. + */ + if ( is_wp_error( rest_validate_value_from_schema( $value, $setting['schema'] ) ) ) { + continue; + } + + $value = rest_sanitize_value_from_schema( $value, $setting['schema'] ); + if ( is_wp_error( rest_validate_value_from_schema( $value, $setting['schema'] ) ) ) { + continue; + } + + // Object (not array()) so an empty object value is serialized as {}, consistent with type:object. + $result[ $exposed_name ] = 'object' === $setting['schema']['type'] ? (object) $value : $value; + } + + return $result; + } + + /** + * Builds the input schema for the `core/settings-get` ability: optional filters by group and/or name. + * + * @since x.x.x + * + * @param list $groups Available settings groups. + * @param list $field_names Available exposed setting names. + * @return array The input JSON Schema. + */ + private function get_settings_get_input_schema( array $groups, array $field_names ): array { + return array( + 'type' => 'object', + 'default' => array(), + 'properties' => array( + 'group' => array( + 'type' => 'string', + 'enum' => $groups, + 'description' => __( 'Return only settings that belong to this settings group. If omitted, settings of every group are returned.' ), + ), + 'fields' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'items' => array( + 'type' => 'string', + 'enum' => $field_names, + ), + 'description' => __( 'Return only the settings with these names. If omitted or empty, all settings allowed by the group filter are returned. When both filters are given, only settings matching both are returned.' ), + ), + ), + 'additionalProperties' => false, + ); + } + + /** + * Builds the output schema for the `core/settings-get` ability. + * + * @since x.x.x + * + * @return array The output JSON Schema. + */ + private function get_settings_get_output_schema(): array { + return array( + 'type' => 'object', + 'description' => __( 'A map of setting name to its current value.' ), + 'properties' => wp_list_pluck( $this->exposed_settings, 'schema' ), + 'additionalProperties' => false, + ); + } + + /** + * Returns the settings exposed through the Abilities API. + * + * @since x.x.x + * + * @return array}> Settings keyed by exposed name. + */ + private function get_exposed_settings(): array { + $settings = array(); + + foreach ( get_registered_settings() as $option_name => $args ) { + if ( empty( $args['show_in_abilities'] ) ) { + continue; + } + + $show = $this->get_exposure_args( $args ); + + $schema = $this->value_schema( $args, $show ); + if ( ! in_array( $schema['type'], array( 'number', 'integer', 'string', 'boolean', 'array', 'object' ), true ) ) { + continue; + } + + $option_name = (string) $option_name; + $exposed_name = empty( $show['name'] ) ? $option_name : (string) $show['name']; + + if ( isset( $settings[ $exposed_name ] ) ) { + _doing_it_wrong( + __METHOD__, + sprintf( + /* translators: 1: Option name, 2: Setting name exposed to abilities, 3: Option name. */ + __( 'The "%1$s" setting is exposed to abilities as "%2$s", a name already used by the "%3$s" setting, which is no longer exposed.' ), + esc_html( $option_name ), + esc_html( $exposed_name ), + esc_html( $settings[ $exposed_name ]['option'] ) + ), + '7.2.0' + ); + } + + $settings[ $exposed_name ] = array( + 'option' => $option_name, + 'group' => $args['group'] ?? '', + 'default' => $args['default'] ?? null, + 'schema' => $schema, + ); + } + + return $settings; + } + + /** + * Returns the name and schema overrides used to expose a setting to abilities. + * + * @since x.x.x + * + * @param array $args The setting registration arguments. + * @return array The exposure arguments, with optional `name` and `schema` keys. + */ + private function get_exposure_args( array $args ): array { + if ( is_array( $args['show_in_abilities'] ) ) { + return $args['show_in_abilities']; + } + + return is_array( $args['show_in_rest'] ) ? $args['show_in_rest'] : array(); + } + + /** + * Builds the JSON Schema describing a single setting's value. + * + * @since x.x.x + * + * @param array $args The setting registration arguments. + * @param array $show The exposure arguments, see get_exposure_args(). + * @return array The value JSON Schema. + */ + private function value_schema( array $args, $show ): array { + $schema = array( + 'type' => $args['type'], + ); + if ( ! empty( $args['label'] ) ) { + $schema['title'] = $args['label']; + } + if ( ! empty( $args['description'] ) ) { + $schema['description'] = $args['description']; + } + if ( isset( $show['schema'] ) && is_array( $show['schema'] ) ) { + /** @var array $show_schema */ + $show_schema = $show['schema']; + $schema = array_merge( $schema, $show_schema ); + } + + return rest_default_additional_properties_to_false( $schema ); + } +} From 7d14ff28164bd6d3b087fbde4201cb111c18a478 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:26:58 -0600 Subject: [PATCH 02/14] Add the site category --- src/Categories.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Categories.php b/src/Categories.php index 4868dd9..7063200 100644 --- a/src/Categories.php +++ b/src/Categories.php @@ -38,6 +38,10 @@ final class Categories { * @var array */ private const DEFINITIONS = array( + 'site' => array( + 'label' => 'Site', + 'description' => 'Abilities that retrieve or modify site information and settings.', + ), 'content' => array( 'label' => 'Content', 'description' => 'Abilities that retrieve or manage posts and other content.', From 472f8bd015c48d504e88d9fdf1d1a83be39bb8a7 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:27:59 -0600 Subject: [PATCH 03/14] Add the ability to our manifest --- src/Manifest.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/Manifest.php b/src/Manifest.php index a4eaa22..d85c7fd 100644 --- a/src/Manifest.php +++ b/src/Manifest.php @@ -60,6 +60,18 @@ public static function all(): array { // the landed core work (wordpress-develop PR 12195) before release. 'proposal' => 'https://github.com/WordPress/wordpress-develop/pull/12195', ), + 'core/settings-get' => array( + 'name' => 'core/settings-get', + 'class' => Settings\Settings_Get::class, + 'category' => 'site', + 'tier' => self::TIER_CORE, + 'min_wp_version' => '6.9', + 'core_since' => '7.2', + 'requires' => array( 'setting_show_in_abilities' ), + 'renamed_from' => null, + // Landed in trunk as b6512b1e8c (Trac #64605), developed in this PR. + 'proposal' => 'https://github.com/WordPress/wordpress-develop/pull/12141', + ), /* * The write trio below is a faithful port of WordPress/ai PR #1025 * (author @jorgefilipecosta), on the package's dotted field paths. From ad04c0cd76618c77cf5d3b629b1eea3cd388874a Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:30:34 -0600 Subject: [PATCH 04/14] Polyfill the show_in_abilities settings arg --- src/Support/Features.php | 25 ++- .../polyfills/setting-show-in-abilities.php | 173 ++++++++++++++++++ 2 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 src/Support/polyfills/setting-show-in-abilities.php diff --git a/src/Support/Features.php b/src/Support/Features.php index 67215cd..c58a3a9 100644 --- a/src/Support/Features.php +++ b/src/Support/Features.php @@ -26,7 +26,8 @@ final class Features { * @var array */ private static $polyfills = array( - 'show_in_abilities' => 'polyfills/show-in-abilities.php', + 'show_in_abilities' => 'polyfills/show-in-abilities.php', + 'setting_show_in_abilities' => 'polyfills/setting-show-in-abilities.php', ); /** @@ -52,6 +53,10 @@ public static function is_available( string $feature ): bool { return self::is_show_in_abilities_available(); } + if ( 'setting_show_in_abilities' === $feature ) { + return self::is_setting_show_in_abilities_available(); + } + return false; } @@ -93,4 +98,22 @@ private static function is_show_in_abilities_available(): bool { return isset( self::$loaded['show_in_abilities'] ); } + + /** + * Detects the `show_in_abilities` setting registration argument. + * + * Core declares it in register_setting() since 7.2, together with + * _wp_register_initial_settings_for_abilities(), which flags and registers + * core's own settings before the abilities read them; the function is the + * detectable half. + * + * @return bool + */ + private static function is_setting_show_in_abilities_available(): bool { + if ( function_exists( '_wp_register_initial_settings_for_abilities' ) ) { + return true; + } + + return isset( self::$loaded['setting_show_in_abilities'] ); + } } diff --git a/src/Support/polyfills/setting-show-in-abilities.php b/src/Support/polyfills/setting-show-in-abilities.php new file mode 100644 index 0000000..6871b0b --- /dev/null +++ b/src/Support/polyfills/setting-show-in-abilities.php @@ -0,0 +1,173 @@ + $args Registration arguments for the setting. + * @param array $defaults Default registration arguments. + * @param string $option_group The settings group. + * @param string $option_name The option name. + * @return array The filtered registration arguments. + */ +$wordpress_abilities_setting_show_in_abilities_polyfill = static function ( $args, $defaults, $option_group, $option_name ) use ( $wordpress_abilities_exposed_core_settings ) { + if ( ! is_array( $args ) || array_key_exists( 'show_in_abilities', $args ) ) { + return $args; + } + + if ( in_array( $option_name, $wordpress_abilities_exposed_core_settings, true ) ) { + $args['show_in_abilities'] = true; + } + + return $args; +}; + +add_filter( 'register_setting_args', $wordpress_abilities_setting_show_in_abilities_polyfill, 10, 4 ); +unset( $wordpress_abilities_setting_show_in_abilities_polyfill ); + +/* + * Catch-up for core settings registered before this polyfill loaded, such as + * when `rest_api_init` already fired in this request. An explicit value on + * the registered setting is never overridden. + */ +if ( isset( $GLOBALS['wp_registered_settings'] ) && is_array( $GLOBALS['wp_registered_settings'] ) ) { + foreach ( $wordpress_abilities_exposed_core_settings as $polyfill_option_name ) { + if ( isset( $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) + && is_array( $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) + && ! array_key_exists( 'show_in_abilities', $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) ) { + $GLOBALS['wp_registered_settings'][ $polyfill_option_name ]['show_in_abilities'] = true; + } + } + unset( $polyfill_option_name ); +} +unset( $wordpress_abilities_exposed_core_settings ); + +/* + * Registers core's initial settings now, as trunk's + * _wp_register_initial_settings_for_abilities() does on `wp_abilities_api_init`, + * plus the privacy policy page setting older hosts lack. Registering a setting + * also allows it on the options screen of its group, so the list is restored + * afterwards: saving Settings > General must not try to save `admin_email`, + * which that screen sends as `new_admin_email`. + */ +$polyfill_allowed_options = $GLOBALS['new_allowed_options'] ?? null; + +if ( ! did_action( 'rest_api_init' ) || doing_action( 'rest_api_init' ) ) { + register_initial_settings(); +} + +if ( ! isset( get_registered_settings()['wp_page_for_privacy_policy'] ) ) { + register_setting( + 'reading', + 'wp_page_for_privacy_policy', + array( + 'show_in_rest' => false, + 'show_in_abilities' => array( + 'name' => 'page_for_privacy_policy', + ), + 'type' => 'integer', + 'description' => __( 'The ID of the page that should be displayed as the privacy policy page' ), + ) + ); + + /* + * Trunk registers it right after `page_for_posts`, and the registration order is the + * order of the exposed settings in the ability's schemas and output. + */ + if ( isset( $GLOBALS['wp_registered_settings']['page_for_posts'] ) ) { + $polyfill_settings = array(); + foreach ( $GLOBALS['wp_registered_settings'] as $polyfill_option_name => $polyfill_setting ) { + if ( 'wp_page_for_privacy_policy' === $polyfill_option_name ) { + continue; + } + $polyfill_settings[ $polyfill_option_name ] = $polyfill_setting; + if ( 'page_for_posts' === $polyfill_option_name ) { + $polyfill_settings['wp_page_for_privacy_policy'] = $GLOBALS['wp_registered_settings']['wp_page_for_privacy_policy']; + } + } + $GLOBALS['wp_registered_settings'] = $polyfill_settings; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Same settings, reordered to trunk's registration order. + unset( $polyfill_settings, $polyfill_option_name, $polyfill_setting ); + } +} + +$GLOBALS['new_allowed_options'] = $polyfill_allowed_options; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restores the core global to its state before the early registration, as trunk does. +unset( $polyfill_allowed_options ); From 1e6bf90f5cde71910325e651964b958e537ced2d Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:32:43 -0600 Subject: [PATCH 05/14] Add new capability checks to ensure we don't register things if we shouldn't, matching some changes made in WP 7.2 --- src/Abstract_Core_Ability.php | 110 +++++++++++++++++++++++++++++----- src/Registrar.php | 15 ++++- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/src/Abstract_Core_Ability.php b/src/Abstract_Core_Ability.php index c3f5ac5..5a25aa1 100644 --- a/src/Abstract_Core_Ability.php +++ b/src/Abstract_Core_Ability.php @@ -83,9 +83,13 @@ abstract protected function make_execute_callback(): callable; * Handles row/status-level checks and must fail closed on malformed * input. Return false or a WP_Error to deny. * - * @return callable(mixed): (bool|\WP_Error) + * Return null when the required capabilities fully own authorization, as + * core allows since 7.2 for an ability that declares a non-empty + * `required_capabilities` list and no `permission_callback`. + * + * @return (callable(mixed): (bool|\WP_Error))|null */ - abstract protected function make_permission_callback(): callable; + abstract protected function make_permission_callback(): ?callable; /** * The ability meta authored by this ability. @@ -111,6 +115,29 @@ abstract protected function ability_meta(): array; */ abstract protected function required_capabilities(): array; + /** + * Computes the registration-time state the other authoring methods read. + * + * Called once, first, by the constructor. Mirrors the state core computes + * in its register() entry point before registering the ability, such as + * a snapshot that the input schema, output schema, and execute callback + * must all share. Most abilities have none and keep this no-op. + */ + protected function prepare(): void {} + + /** + * Whether the ability should be registered at all. + * + * Mirrors the early return core takes in its register() entry + * point, for example when there is nothing to expose. Most + * abilities always register and keep the default. + * + * @return bool True to register the ability. + */ + public function should_register(): bool { + return true; + } + /** * Provenance meta merged into every ability of this package. * @@ -160,20 +187,73 @@ final public function __construct( ?string $name = null, array $args = array() ) ); } - parent::__construct( - $ability_name, - array( - 'label' => $this->label(), - 'description' => $this->description(), - 'category' => $this->category_slug(), - 'input_schema' => $this->input_schema(), - 'output_schema' => $this->output_schema(), - 'execute_callback' => $this->make_execute_callback(), - 'permission_callback' => $this->make_permission_callback(), - 'required_capabilities' => $this->required_capabilities(), - 'meta' => $this->merge_meta( $args ), - ) + $this->prepare(); + + $properties = array( + 'label' => $this->label(), + 'description' => $this->description(), + 'category' => $this->category_slug(), + 'input_schema' => $this->input_schema(), + 'output_schema' => $this->output_schema(), + 'execute_callback' => $this->make_execute_callback(), + 'meta' => $this->merge_meta( $args ), ); + + $permission_callback = $this->make_permission_callback(); + $required_capabilities = $this->required_capabilities(); + + if ( self::host_checks_required_capabilities() ) { + $properties['permission_callback'] = $permission_callback; + $properties['required_capabilities'] = $required_capabilities; + } else { + $properties['permission_callback'] = self::with_capability_floor( $required_capabilities, $permission_callback ); + } + + parent::__construct( $ability_name, $properties ); + } + + /** + * Whether the host's WP_Ability checks `required_capabilities` itself. + * + * Core added the argument in 7.2. Older hosts reject it as an unknown + * property and would never check the floor, so the constructor folds the + * floor into the permission callback there instead. + * + * @return bool True when the host declares the `required_capabilities` property. + */ + private static function host_checks_required_capabilities(): bool { + return property_exists( WP_Ability::class, 'required_capabilities' ); + } + + /** + * Wraps a permission callback with the required capabilities check. + * + * Mirrors WP_Ability::check_permissions() on 7.2+: every required + * capability is checked first, and the permission callback runs only + * when all of them pass. Without a permission callback, the floor alone + * decides; an empty floor without a callback fails closed. + * + * @param list $required_capabilities The capability floor. + * @param (callable(mixed): (bool|\WP_Error))|null $permission_callback The authored permission callback. + * @return callable(mixed): (bool|\WP_Error) The combined permission callback. + */ + private static function with_capability_floor( array $required_capabilities, ?callable $permission_callback ): callable { + if ( array() === $required_capabilities ) { + // No floor to fold in: keep the callback, or fail closed without one. + return $permission_callback ?? static function (): bool { + return false; + }; + } + + return static function ( ...$args ) use ( $required_capabilities, $permission_callback ) { + foreach ( $required_capabilities as $capability ) { + if ( ! current_user_can( $capability ) ) { + return false; + } + } + + return null === $permission_callback ? true : $permission_callback( ...$args ); + }; } /** diff --git a/src/Registrar.php b/src/Registrar.php index a063f51..3939fb1 100644 --- a/src/Registrar.php +++ b/src/Registrar.php @@ -374,8 +374,11 @@ private static function declare_categories(): void { * 4. Consumer `filter` selection policy. * 5. WordPress version vs. the entry's min_wp_version support floor. * 6. `public_only`: probe the ability's own `public` meta. - * 7. Support-surface `requires`: every feature must be available, - * attempting a polyfill load when one exists. + * 7. Host readiness: every support-surface `requires` feature must be + * available, attempting a polyfill load when one exists; then the + * ability's own should_register() must agree, read on a probe + * instance once those features are in place (core's register() + * early return, e.g. nothing to expose). * 8. Registration via the core `ability_class` mechanism, merging * provenance meta (stability tier, renamed_from lineage). A null * result from core when the ability's manifest-declared category is @@ -426,13 +429,19 @@ private static function try_register( string $name, array $entry, array $args ): } } - // Gate 7: support-surface features, with polyfill attempt. + // Gate 7: support-surface features, with polyfill attempt, then the + // ability's own registration-time readiness. foreach ( (array) $entry['requires'] as $feature ) { if ( ! Features::is_available( $feature ) && ! Features::load_polyfill( $feature ) ) { return false; } } + $probe = new $entry['class'](); + if ( ! $probe->should_register() ) { + return false; + } + // Gate 8: register via the core `ability_class` mechanism, merging // provenance meta (stability, lineage). $meta = array( From 3576713f4652cfd0277453dad21abdd5dc3e4bf9 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:33:16 -0600 Subject: [PATCH 06/14] Add tests to cover changes --- tests/Abilities/SettingsGetTest.php | 589 ++++++++++++++++++ .../abilities/class-wp-abilities-settings.php | 9 +- tests/RegistrarTest.php | 98 +++ 3 files changed, 692 insertions(+), 4 deletions(-) create mode 100644 tests/Abilities/SettingsGetTest.php diff --git a/tests/Abilities/SettingsGetTest.php b/tests/Abilities/SettingsGetTest.php new file mode 100644 index 0000000..33d2ebe --- /dev/null +++ b/tests/Abilities/SettingsGetTest.php @@ -0,0 +1,589 @@ + + */ + private array $user_ids = array(); + + /** + * Settings registered by a test: option name => group. + * + * @var array + */ + private array $test_settings = array(); + + /** + * Recorded _doing_it_wrong() calls: function => messages. + * + * @var array> + */ + private static array $wrong_usage = array(); + + /** + * Settles the registry as the other ability suites do, and records + * _doing_it_wrong() traffic for the class. + */ + public static function set_up_before_class(): void { + if ( 0 === did_action( 'wp_abilities_api_init' ) ) { + WP_Abilities_Registry::get_instance(); + } + Registrar::register_all(); + + add_action( + 'doing_it_wrong_run', + static function ( string $function_name, string $message ): void { + self::$wrong_usage[ $function_name ][] = $message; + }, + 10, + 2 + ); + } + + /** + * Removes the test settings, their options, and the mocked users. + */ + public function tear_down(): void { + foreach ( $this->test_settings as $option_name => $group ) { + unregister_setting( $group, $option_name ); + delete_option( $option_name ); + } + $this->test_settings = array(); + + if ( ! empty( $this->user_ids ) && ! function_exists( 'wp_delete_user' ) ) { + require_once ABSPATH . 'wp-admin/includes/user.php'; + } + foreach ( $this->user_ids as $id ) { + if ( $id > 1 ) { + wp_delete_user( $id ); + } + } + $this->user_ids = array(); + wp_set_current_user( 0 ); + self::$wrong_usage = array(); + + parent::tear_down(); + } + + /** + * The registered `core/settings-get` instance, or null. + */ + private function get_registered(): ?WP_Ability { + return WP_Abilities_Registry::get_instance()->get_registered( 'core/settings-get' ); + } + + /** + * Logs in a mocked user of the given role. + */ + private function log_in_as( string $role ): void { + if ( ! isset( $this->user_ids[ $role ] ) ) { + $this->user_ids[ $role ] = (int) wp_insert_user( + array( + 'user_login' => 'sg' . $role, + 'user_pass' => wp_generate_password(), + 'role' => $role, + ) + ); + } + wp_set_current_user( $this->user_ids[ $role ] ); + } + + /** + * Registers a test setting, tracked for removal. + * + * @param string $group The settings group. + * @param string $option_name The option name. + * @param array $args The registration args. + */ + private function add_setting( string $group, string $option_name, array $args ): void { + register_setting( $group, $option_name, $args ); + $this->test_settings[ $option_name ] = $group; + } + + /** + * Asserts a WP_Error with the exact code. + */ + private function assert_wp_error( string $code, $actual ): void { + self::assertInstanceOf( WP_Error::class, $actual, "Expected WP_Error {$code}." ); + self::assertSame( $code, $actual->get_error_code() ); + } + + /** + * Runs a callback with PHP notices silenced, so an expected + * _doing_it_wrong() E_USER_NOTICE cannot fail the test; the + * doing_it_wrong_run action still fires and is recorded. + * + * @param callable $callback The function to run. + * @return mixed The callback result. + */ + private static function silence_notices( callable $callback ) { + set_error_handler( static fn (): bool => true, E_USER_NOTICE ); + try { + return $callback(); + } finally { + restore_error_handler(); + } + } + + /** + * The _doing_it_wrong() messages recorded for a function since the last reset. + * + * @param string $function_name The function the notice names. + * @return list The recorded messages. + */ + private static function recorded_wrong_usage( string $function_name ): array { + return self::$wrong_usage[ $function_name ] ?? array(); + } + + /** + * Registered exactly once, with core's annotations; provenance branches by env; + * repeat registration never double-registers. + */ + public function test_registered_once_with_core_annotations(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $meta = $ability->get_meta(); + + self::assertSame( 'site', $ability->get_category() ); + self::assertSame( + array( + 'readonly' => true, + 'destructive' => false, + 'idempotent' => true, + ), + $meta['annotations'] ?? null + ); + self::assertTrue( (bool) ( $meta['public'] ?? false ) ); + + if ( empty( $meta['source'] ) ) { + // Trunk env: core provides the name; the package copy must have skipped. + self::assertNotInstanceOf( Settings_Get::class, $ability ); + } else { + // Stable env: the package copy registered. + self::assertInstanceOf( Settings_Get::class, $ability ); + self::assertSame( 'wordpress/abilities', $meta['source'] ); + self::assertSame( Manifest::VERSION, $meta['package_version'] ?? null ); + self::assertSame( Manifest::TIER_CORE, $meta['stability'] ?? null ); + } + + Registrar::register_all(); + Registrar::register_all(); + self::assertSame( $ability, $this->get_registered(), 'No double registration: the single instance holds.' ); + } + + /** + * Trunk's `manage_options` floor, read back from the host or the package copy. + */ + public function test_required_capabilities_mirror_trunk(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + if ( method_exists( $ability, 'get_required_capabilities' ) ) { + // 7.2+ hosts (trunk core): the floor is stored and read back. + self::assertSame( array( 'manage_options' ), $ability->get_required_capabilities() ); + } else { + // Host API predates 7.2: assert the package copy's authored floor reflectively. + self::assertSame( + array( 'manage_options' ), + ( new ReflectionClass( $ability ) )->getMethod( 'required_capabilities' )->invoke( $ability ) + ); + } + } + + /** + * The registered copy exposes exactly trunk's core settings, in trunk's order, + * and the input and output schemas are built from them. + */ + public function test_schemas_expose_trunk_core_settings(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + + $input = $ability->get_input_schema(); + self::assertSame( 'object', $input['type'] ); + self::assertSame( array(), $input['default'] ); + self::assertFalse( $input['additionalProperties'] ); + self::assertSame( array( 'group', 'fields' ), array_keys( $input['properties'] ) ); + self::assertSame( array( 'general', 'writing', 'reading', 'discussion' ), $input['properties']['group']['enum'] ); + self::assertTrue( $input['properties']['fields']['uniqueItems'] ); + self::assertSame( self::TRUNK_EXPOSED, $input['properties']['fields']['items']['enum'] ); + + $output = $ability->get_output_schema(); + self::assertSame( 'object', $output['type'] ); + self::assertFalse( $output['additionalProperties'] ); + self::assertSame( self::TRUNK_EXPOSED, array_keys( $output['properties'] ) ); + self::assertSame( array( 'open', 'closed' ), $output['properties']['default_comment_status']['enum'] ); + self::assertSame( 'email', $output['properties']['email']['format'] ); + self::assertSame( 'integer', $output['properties']['page_for_privacy_policy']['type'] ); + } + + /** + * Permission gate: logged out, subscriber, and editor are denied (negative); + * an administrator is allowed (positive). On stable this runs through the + * capability floor the package folds into the permission callback. + */ + public function test_permission_negative_and_positive(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + + wp_set_current_user( 0 ); + self::assertFalse( $ability->check_permissions( array() ) ); + $this->assert_wp_error( 'ability_invalid_permissions', $ability->execute( array() ) ); + + foreach ( array( 'subscriber', 'editor' ) as $role ) { + $this->log_in_as( $role ); + self::assertFalse( $ability->check_permissions( array() ), "A {$role} lacks manage_options." ); + } + + $this->log_in_as( 'administrator' ); + self::assertTrue( $ability->check_permissions( array() ) ); + $result = $ability->execute( array( 'fields' => array( 'title' ) ) ); + self::assertSame( array( 'title' => get_option( 'blogname' ) ), $result ); + } + + /** + * Malformed or unknown input fails closed at schema validation, never widened. + */ + public function test_execute_fail_closed_malformed_input(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $this->log_in_as( 'administrator' ); + + $this->assert_wp_error( 'ability_invalid_input', $ability->execute( array( 'group' => 'no-such-group' ) ) ); + $this->assert_wp_error( 'ability_invalid_input', $ability->execute( array( 'fields' => array( 'no_such_setting' ) ) ) ); + $this->assert_wp_error( 'ability_invalid_input', $ability->execute( array( 'fields' => array( 'title', 'title' ) ) ) ); + $this->assert_wp_error( 'ability_invalid_input', $ability->execute( array( 'unknown' => true ) ) ); + $this->assert_wp_error( 'ability_invalid_input', $ability->execute( 'title' ) ); + + $all = $ability->execute( array() ); + self::assertIsArray( $all ); + self::assertSame( array_intersect( self::TRUNK_EXPOSED, array_keys( $all ) ), array_keys( $all ), 'No input returns exposed settings only, in order.' ); + } + + /** + * Execute against mocked settings: exposure names, defaults, the boolean and + * object reads, schema-invalid values, and the group/fields filters. + */ + public function test_execute_mocked_settings(): void { + $this->add_setting( + 'sg_a', + 'sg_string', + array( + 'type' => 'string', + 'show_in_abilities' => true, + 'default' => 'fallback', + ) + ); + $this->add_setting( + 'sg_a', + 'sg_no_default', + array( + 'type' => 'integer', + 'show_in_abilities' => true, + ) + ); + $this->add_setting( + 'sg_b', + 'sg_bool', + array( + 'type' => 'boolean', + 'show_in_abilities' => true, + ) + ); + $this->add_setting( + 'sg_b', + 'sg_invalid', + array( + 'type' => 'integer', + 'show_in_abilities' => true, + ) + ); + $this->add_setting( + 'sg_b', + 'sg_object', + array( + 'type' => 'object', + 'show_in_abilities' => array( + 'schema' => array( + 'properties' => array( + 'a' => array( 'type' => 'string' ), + ), + ), + ), + ) + ); + $this->add_setting( + 'sg_b', + 'sg_rest_named', + array( + 'type' => 'string', + 'show_in_rest' => array( 'name' => 'sg_rest_name' ), + 'show_in_abilities' => true, + ) + ); + $this->add_setting( + 'sg_b', + 'sg_abilities_named', + array( + 'type' => 'string', + 'show_in_rest' => array( 'name' => 'sg_ignored_rest_name' ), + 'show_in_abilities' => array( 'name' => 'sg_abilities_name' ), + ) + ); + $this->add_setting( + 'sg_b', + 'sg_hidden', + array( + 'type' => 'string', + 'show_in_abilities' => false, + ) + ); + // update_option() skips a missing option whose new value is false; add_option() stores it as ''. + add_option( 'sg_bool', false ); + update_option( 'sg_invalid', 'not-a-number' ); + update_option( 'sg_object', array( 'a' => 'x' ) ); + update_option( 'sg_rest_named', 'rest' ); + update_option( 'sg_abilities_named', 'abilities' ); + update_option( 'sg_hidden', 'hidden' ); + + $this->log_in_as( 'administrator' ); + $ability = new Settings_Get(); + self::assertTrue( $ability->should_register() ); + + $result = $ability->execute( array( 'group' => 'sg_a' ) ); + self::assertSame( array( 'sg_string' => 'fallback' ), $result, 'An unsaved setting reads its default, or is left out without one.' ); + + $result = $ability->execute( array( 'group' => 'sg_b' ) ); + self::assertIsArray( $result ); + self::assertSame( array( 'sg_bool', 'sg_object', 'sg_rest_name', 'sg_abilities_name' ), array_keys( $result ) ); + self::assertFalse( $result['sg_bool'], 'A stored false reads as false, not the empty string.' ); + self::assertInstanceOf( stdClass::class, $result['sg_object'] ); + self::assertSame( 'x', $result['sg_object']->a ); + self::assertSame( 'rest', $result['sg_rest_name'], 'show_in_abilities: true uses the show_in_rest name.' ); + self::assertSame( 'abilities', $result['sg_abilities_name'], 'A show_in_abilities array is used instead of show_in_rest.' ); + self::assertArrayNotHasKey( 'sg_invalid', $result, 'A value its schema rejects is left out.' ); + + self::assertSame( array( 'sg_bool' => false ), $ability->execute( array( 'fields' => array( 'sg_bool' ) ) ) ); + self::assertSame( + array(), + $ability->execute( + array( + 'group' => 'sg_a', + 'fields' => array( 'sg_bool' ), + ) + ), + 'Both filters narrow to their intersection.' + ); + + $fields = $ability->get_input_schema()['properties']['fields']['items']['enum']; + self::assertNotContains( 'sg_hidden', $fields ); + self::assertNotContains( 'sg_ignored_rest_name', $fields ); + self::assertSame( 'string', $ability->get_output_schema()['properties']['sg_string']['type'] ); + } + + /** + * Two settings exposed under the same name: a notice, and the later one wins. + */ + public function test_duplicate_exposed_name_is_reported(): void { + $this->add_setting( + 'sg_dup', + 'sg_dup_first', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => 'sg_dup' ), + ) + ); + $this->add_setting( + 'sg_dup', + 'sg_dup_second', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => 'sg_dup' ), + ) + ); + update_option( 'sg_dup_first', 'first' ); + update_option( 'sg_dup_second', 'second' ); + + self::$wrong_usage = array(); + $ability = self::silence_notices( + static function (): Settings_Get { + return new Settings_Get(); + } + ); + + $notices = self::recorded_wrong_usage( Settings_Get::class . '::get_exposed_settings' ); + self::assertCount( 1, $notices ); + self::assertStringContainsString( 'sg_dup_second', $notices[0] ); + + $this->log_in_as( 'administrator' ); + self::assertSame( array( 'sg_dup' => 'second' ), $ability->execute( array( 'fields' => array( 'sg_dup' ) ) ) ); + } + + /** + * should_register() mirrors core's early return when no setting is exposed. + */ + public function test_should_register_only_with_exposed_settings(): void { + $backup = $GLOBALS['wp_registered_settings']; + + try { + $GLOBALS['wp_registered_settings'] = array(); + $ability = new Settings_Get(); + self::assertFalse( $ability->should_register() ); + } finally { + $GLOBALS['wp_registered_settings'] = $backup; + } + + self::assertTrue( ( new Settings_Get() )->should_register() ); + } + + /** + * Constructing the package copy raises no notice on either host: the + * `required_capabilities` argument only reaches a WP_Ability that declares it. + */ + public function test_construction_raises_no_wrong_usage(): void { + self::$wrong_usage = array(); + new Settings_Get(); + self::assertSame( array(), self::$wrong_usage ); + } + + /** + * The capability floor the package folds into the permission callback on + * hosts older than 7.2, mirroring WP_Ability::check_permissions() on 7.2+. + */ + public function test_capability_floor_mirrors_core_check_order(): void { + $fold = new ReflectionMethod( Abstract_Core_Ability::class, 'with_capability_floor' ); + $fold->setAccessible( true ); // No-op on PHP 8.1+, required on 7.4. + + $calls = array(); + $callback = static function ( $input = null ) use ( &$calls ): bool { + $calls[] = $input; + return 'allow' === $input; + }; + + self::assertSame( $callback, $fold->invoke( null, array(), $callback ), 'No floor: the callback is kept as-is.' ); + self::assertFalse( $fold->invoke( null, array(), null )(), 'No floor and no callback fails closed.' ); + + $floor_only = $fold->invoke( null, array( 'manage_options' ), null ); + $combined = $fold->invoke( null, array( 'manage_options' ), $callback ); + + $this->log_in_as( 'subscriber' ); + self::assertFalse( $floor_only() ); + self::assertFalse( $combined( 'allow' ) ); + self::assertSame( array(), $calls, 'The callback never runs when the floor fails.' ); + + $this->log_in_as( 'administrator' ); + self::assertTrue( $floor_only() ); + self::assertTrue( $combined( 'allow' ) ); + self::assertFalse( $combined( 'deny' ) ); + self::assertSame( array( 'allow', 'deny' ), $calls, 'The callback runs after the floor, with the input forwarded.' ); + } + + /** + * The support feature: native on 7.2+, polyfilled on 6.9-7.1. + */ + public function test_setting_show_in_abilities_feature(): void { + self::assertTrue( Features::is_available( 'setting_show_in_abilities' ) ); + + $loaded = ( new ReflectionClass( Features::class ) )->getProperty( 'loaded' ); + $loaded->setAccessible( true ); // No-op on PHP 8.1+, required on 7.4. + $native = function_exists( '_wp_register_initial_settings_for_abilities' ); + self::assertSame( ! $native, isset( $loaded->getValue()['setting_show_in_abilities'] ), 'The polyfill loads only where core lacks the feature.' ); + } + + /** + * The polyfill (6.9-7.1 only): trunk's default for core settings, explicit + * values kept, the privacy page setting registered for abilities only, and + * the options screens' allowed list left alone. + */ + public function test_polyfill_mirrors_trunk_defaults(): void { + if ( function_exists( '_wp_register_initial_settings_for_abilities' ) ) { + self::markTestSkipped( 'Core provides the setting argument; the polyfill never loads here.' ); + } + + $filtered = apply_filters( 'register_setting_args', array( 'type' => 'string' ), array(), 'general', 'blogname' ); + self::assertTrue( $filtered['show_in_abilities'] ); + + $explicit = apply_filters( + 'register_setting_args', + array( + 'type' => 'string', + 'show_in_abilities' => false, + ), + array(), + 'general', + 'blogname' + ); + self::assertFalse( $explicit['show_in_abilities'], 'An explicit value is never overridden.' ); + + $other = apply_filters( 'register_setting_args', array( 'type' => 'string' ), array(), 'general', 'sg_not_core' ); + self::assertArrayNotHasKey( 'show_in_abilities', $other, 'Only the settings trunk exposes get the default.' ); + + $privacy = get_registered_settings()['wp_page_for_privacy_policy'] ?? null; + self::assertIsArray( $privacy ); + self::assertFalse( $privacy['show_in_rest'], 'The REST settings endpoint of the host is unchanged.' ); + self::assertSame( array( 'name' => 'page_for_privacy_policy' ), $privacy['show_in_abilities'] ); + + self::assertNotContains( + 'wp_page_for_privacy_policy', + $GLOBALS['new_allowed_options']['reading'] ?? array(), + 'Registering for abilities does not add the setting to an options screen.' + ); + } +} diff --git a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-settings.php b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-settings.php index b92cfc0..56901bd 100644 --- a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-settings.php +++ b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-settings.php @@ -2,11 +2,12 @@ /** * TRUNK SNAPSHOT — manually refreshed copy from WordPress/wordpress-develop trunk. * Original core path (for refresh): src/wp-includes/abilities/class-wp-abilities-settings.php - * Refreshed: 2026-10-20 by WP2 (test infrastructure). + * Refreshed: 2026-10-20 by WP2 (test infrastructure); re-verified identical + * to trunk 2026-10-23 (WP7). * - * Tracked trunk reference kept in place for the planned `core/settings-get` - * backport (a future coreify round-trip reference; the gate currently reads - * the content snapshot). Only this file-level header is package-local; the + * Tracked trunk reference for the coreify round-trip gate of the + * `core/settings-get` backport: tools/coreify.php --check reads this file + * for that profile. Only this file-level header is package-local; the * code body below stays byte-faithful to trunk. Never loaded as code * anymore: the Abilities API ships in WordPress core since 6.9 and the * tests assume it. NOT package code: never shipped, never autoloaded. diff --git a/tests/RegistrarTest.php b/tests/RegistrarTest.php index 6a44742..d33bc44 100644 --- a/tests/RegistrarTest.php +++ b/tests/RegistrarTest.php @@ -914,4 +914,102 @@ static function (): void { self::assertSame( array(), $registrar_traffic, 'P8: the restored boot registers without any Registrar wrong-usage traffic.' ); self::reset_wrong_usage(); } + + /** + * 10. Gate 7 readiness: an ability whose should_register() declines (core's + * register() early return, e.g. nothing to expose) is skipped silently and + * never reaches the registry, once its support-surface features pass. + */ + public function test_readiness_gate_skips_declining_ability(): void { + $declining = new class() extends Abstract_Core_Ability { + + /** + * The full ability name, including its tier prefix. + */ + protected function ability_name(): string { + return 'test/registrar-declining'; + } + + /** + * The human-readable ability label. + */ + protected function label(): string { + return 'Registrar test declining ability'; + } + + /** + * A detailed description of what the ability does. + */ + protected function description(): string { + return 'Synthetic ability whose readiness check declines registration. Never ships in the manifest.'; + } + + /** + * The ability category slug. + */ + protected function category_slug(): string { + return 'content'; + } + + /** + * The JSON Schema definition for the ability's input. + */ + protected function input_schema(): array { + return array(); + } + + /** + * The JSON Schema definition for the ability's output. + */ + protected function output_schema(): array { + return array(); + } + + /** + * Builds the execute callback. + */ + protected function make_execute_callback(): callable { + return static function (): array { + return array(); + }; + } + + /** + * No permission callback: the floor owns authorization. + */ + protected function make_permission_callback(): ?callable { + return null; + } + + /** + * The ability meta. + */ + protected function ability_meta(): array { + return array( 'public' => true ); + } + + /** + * The request-level capability floor. + */ + protected function required_capabilities(): array { + return array( 'manage_options' ); + } + + /** + * Declines registration, as core's register() returns early. + */ + public function should_register(): bool { + return false; + } + }; + + $entry = self::synthetic_entry(); + $entry['name'] = 'test/registrar-declining'; + $entry['class'] = get_class( $declining ); + + self::reset_wrong_usage(); + self::assertFalse( self::try_register_entry( 'test/registrar-declining', $entry ), 'A declining ability is skipped.' ); + self::assertFalse( wp_has_ability( 'test/registrar-declining' ), 'A declining ability never reaches the registry.' ); + self::assert_no_wrong_usage( 'The readiness skip is silent.' ); + } } From be4bd6ef50970d4153feffa7f8cb2856b5274dfc Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:33:34 -0600 Subject: [PATCH 07/14] Stub get_registered_settings --- .stubs/abilities-api.php | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/.stubs/abilities-api.php b/.stubs/abilities-api.php index 267d88d..3b26b9f 100644 --- a/.stubs/abilities-api.php +++ b/.stubs/abilities-api.php @@ -11,7 +11,9 @@ * 6.9 ( wordpress-develop trunk as of 2026-10-20: WP_Ability, * WP_Abilities_Registry, WP_Ability_Categories_Registry, * WP_Ability_Category, and the global API functions; the former test - * fixture shim files these were once mirrored against are removed). + * fixture shim files these were once mirrored against are removed), plus + * the 7.2 shape of get_registered_settings(), which the API's settings + * abilities read. * Once phpstan-wordpress ships Abilities API stubs, delete this file and its * stubFiles entry. * @@ -192,4 +194,29 @@ function wp_register_ability_category( string $slug, array $args ) { function wp_has_ability_category( string $slug ) { return false; } + + /** + * Retrieves an array of registered settings. + * + * Overrides the phpstan-wordpress shape, which predates 7.2: trunk's registered + * setting data adds the `show_in_abilities` argument, and the `group` and `default` + * keys are not always present. Mirrors trunk's wp-includes/option.php docblock. + * + * @since 4.7.0 + * @since 7.2.0 Registered setting data includes the `show_in_abilities` argument. + * + * @phpstan-return array, + * show_in_abilities?: bool|array, + * default?: mixed, + * }> + */ + function get_registered_settings() { + return array(); + } } From e3b0eaf230e76a2c522a84a76ec01d976eefeec9 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:34:29 -0600 Subject: [PATCH 08/14] Update docs --- CONTRIBUTING.md | 10 ++++++---- KNOWN-ISSUES.md | 10 ++++++++++ README.md | 6 +++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0ba8244..1940be3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -74,10 +74,12 @@ registration under the old name are **rejected** — no exceptions, ever. deliberately carries no version field — and must match the newest git tag when tags exist, else the `0.1.0` seed). - `verify:coreify` — the coreify round-trip gate (`tools/coreify.php - --check`): reverse of the trunk fixture followed by forward must - reproduce the original core file, and the reverse output must match the - hand-port `src/Content/Content_Query.php`, modulo whitespace and - comments. + --check`), for every tier-core ability with a transform profile + (`core/content-query`, `core/settings-get`): reverse of the trunk fixture + followed by forward must reproduce the original core file, and the + reverse output must match the hand-port (`src/Content/Content_Query.php`, + `src/Settings/Settings_Get.php`), modulo whitespace and comments. A new + tier-core backport adds its profile to `PROFILES` in `tools/coreify.php`. - PHPUnit on both environments — WordPress trunk and latest stable. Both ship the Abilities API in core (the 6.9+ support floor; stable pre-7.2 carries the real pre-7.2 API), so core-skip and backport paths are both diff --git a/KNOWN-ISSUES.md b/KNOWN-ISSUES.md index d9997a2..8ac8c77 100644 --- a/KNOWN-ISSUES.md +++ b/KNOWN-ISSUES.md @@ -8,6 +8,16 @@ This file tracks open items only: an entry is removed once fixed. The closing commit and changelog carry the resolution; git history is the archive of resolved entries. +## Readiness probe constructs the ability twice + +The Registrar reads `should_register()` on a probe instance before the +registry builds its own, so an ability with registration-time state computes +it twice per registration. For `core/settings-get` this is the +exposed-settings snapshot: both snapshots are identical, but a duplicate +exposed setting name fires its `_doing_it_wrong()` notice once per snapshot +(twice, where core fires once). The registry's `ability_class` mechanism +gives no way to hand it the probed instance. + ## Ported-as-is PR behaviors (documented, not fixed) Behaviors inherited verbatim from the upstream PR; intentional for parity diff --git a/README.md b/README.md index ce87eca..faaafad 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ Full rules, the promotion path, and the rename protocol are in | Name | Tier | Category | Notes | |---|---|---|---| | `core/content-query` | core | content | Backport of the readonly content query ability landed in WordPress core 7.2 (`core_since: 7.2`). On 7.2+ core provides it and the Registrar skips it; on 6.9–7.1 the package serves it under the same name. Requires the `show_in_abilities` support feature (polyfilled where core lacks it). | +| `core/settings-get` | core | site | Backport of the readonly settings get ability landed in WordPress core 7.2 (`core_since: 7.2`). On 7.2+ core provides it and the Registrar skips it; on 6.9–7.1 the package serves it under the same name. Requires the `setting_show_in_abilities` support feature (polyfilled where core lacks it: core's own settings are flagged and registered before the ability reads them, as on 7.2). | | `core/content-create` | stable | content | Port of the content create ability from [WordPress/ai PR #1025](https://github.com/WordPress/ai/pull/1025) (`core_since: null` — flips to tier `core` when it lands in WordPress core). Creates posts of types exposed to abilities under the field names `core/content-query` returns. | | `core/content-update` | stable | content | Port of the content update ability from [WordPress/ai PR #1025](https://github.com/WordPress/ai/pull/1025) (`core_since: null` — flips to tier `core` when it lands in WordPress core). Updates a post by ID; fields left out keep their current values. | | `core/content-delete` | stable | content | Port of the content delete ability from [WordPress/ai PR #1025](https://github.com/WordPress/ai/pull/1025) (`core_since: null` — flips to tier `core` when it lands in WordPress core). Trashes a post by ID, or deletes it permanently with `force`. | @@ -93,9 +94,8 @@ Full rules, the promotion path, and the rename protocol are in Planned, **not** available in the current package: the MCP adapter consuming this package via `Registrar::register_all()`; further write abilities -(`wp/post-update`, `wp/post-delete`); `core/users-query` and -`core/settings-get` backports; the WordPress AI plugin migration; Packagist -publishing. +beyond the content trio; the `core/users-query` backport; the WordPress AI +plugin migration; Packagist publishing. ## Development From af2b70111370e1e2550bb217fd9ede495501b7b4 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:35:28 -0600 Subject: [PATCH 09/14] Update the coreify tool to work for settings-get --- tools/coreify.php | 565 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 416 insertions(+), 149 deletions(-) diff --git a/tools/coreify.php b/tools/coreify.php index c2571d7..5c095dd 100644 --- a/tools/coreify.php +++ b/tools/coreify.php @@ -74,18 +74,74 @@ function fail( string $msg ): void { 'execute_callback', 'permission_callback', 'required_capabilities', 'meta', ); +/** + * Optional authoring methods: Abstract_Core_Ability defaults them, and an + * ability overrides them only when core's register() entry point computes + * state before registering (prepare()) or returns early (should_register()). + */ +const OPTIONAL_METHODS = array( 'prepare', 'should_register' ); + /** Helpers re-inlined from Abstract_Core_Ability, in order. */ const INLINE_HELPERS = array( 'parse_filter_int', 'parse_list_input', 'get_input_object' ); -/** Forward anchors: helper name => member after which the helper is inserted. */ -const HELPER_AFTER = array( - 'parse_filter_int' => 'check_permission', - 'parse_list_input' => 'parse_filter_int', - 'get_input_object' => 'execute_content_query', +/** + * Per-ability transform profiles, keyed by ability name. + * + * - fixture / package: repo-relative paths of the trunk snapshot and the + * package port, the --check pair. + * - splice_after: the register_*() prologue variable after which core's + * void early-return guard is spliced (null when core's guard, if any, + * lives in register() instead; that one maps to should_register()). + * - helpers: forward anchors, helper name => member after which the + * inherited Abstract_Core_Ability helper is re-inlined. + * - imports: the fixed `use` block of the package form. + * - register_doc / register_note: the forward register() docblock summary + * and trailing comment (cosmetic; the semantic diff ignores comments). + * - category / requires / proposal: the reverse manifest entry skeleton. + */ +const PROFILES = array( + 'core/content-query' => array( + 'fixture' => 'tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php', + 'package' => 'src/Content/Content_Query.php', + 'splice_after' => '$post_types', + 'helpers' => array( + 'parse_filter_int' => 'check_permission', + 'parse_list_input' => 'parse_filter_int', + 'get_input_object' => 'execute_content_query', + ), + 'imports' => array( 'DateTimeZone', 'stdClass', 'WP_Error', 'WP_Post', 'WP_Post_Type', 'WP_Query', 'WP_User' ), + 'register_doc' => 'Registers all content abilities.', + 'register_note' => array( + 'Future write-oriented content abilities can be registered here, reusing', + 'the shared helpers below (get_exposed_post_type(), format_post(),', + 'check_permission()).', + ), + 'category' => 'content', + 'requires' => array( 'show_in_abilities' ), + 'proposal' => 'https://github.com/WordPress/wordpress-develop/pull/12195', + ), + 'core/settings-get' => array( + 'fixture' => 'tests/Fixtures/abilities-api/abilities/class-wp-abilities-settings.php', + 'package' => 'src/Settings/Settings_Get.php', + 'splice_after' => null, + 'helpers' => array(), + 'imports' => array(), + 'register_doc' => 'Registers all settings abilities.', + 'register_note' => array(), + 'category' => 'site', + 'requires' => array( 'setting_show_in_abilities' ), + 'proposal' => 'https://github.com/WordPress/wordpress-develop/pull/12141', + ), ); -/** Fixed `use` block of the package form (per the hand-port). */ -const PKG_IMPORTS = array( 'DateTimeZone', 'stdClass', 'WP_Error', 'WP_Post', 'WP_Post_Type', 'WP_Query', 'WP_User' ); +/** Ability whose files the forward and reverse modes default to. */ +const DEFAULT_ABILITY = 'core/content-query'; + +/** The transform profile of an ability name. */ +function profile( string $abname ): array { + isset( PROFILES[ $abname ] ) || fail( 'no coreify profile for ability ' . $abname . ' (add one to PROFILES)' ); + return PROFILES[ $abname ]; +} /* --------------------------------------------------------------------- * Token primitives @@ -97,8 +153,8 @@ function fail( string $msg ): void { * * @return list */ -function tokenize_source( string $src ): array { - $raw = token_get_all( $src, TOKEN_PARSE ); +function tokenize_source( string $src, bool $parse = true ): array { + $raw = $parse ? token_get_all( $src, TOKEN_PARSE ) : token_get_all( $src ); $out = array(); $line = 1; foreach ( $raw as $t ) { @@ -440,6 +496,44 @@ function parse_members( array $tokens, int $open, int $close ): array { continue; } $id = $t[0]; + if ( T_VARIABLE === $id ) { + // Property declaration: modifiers (and an optional type) back to the first one. + $p = $i; + while ( true ) { + $pv = prev_meaningful_token( $tokens, $open + 1, $p - 1 ); + if ( null === $pv ) { + break; + } + $pid = $tokens[ $pv ][0]; + if ( T_PUBLIC === $pid || T_PROTECTED === $pid || T_PRIVATE === $pid + || T_STATIC === $pid || T_READONLY === $pid || T_VAR === $pid + || T_STRING === $pid || T_ARRAY === $pid || 63 === $pid ) { // 63: '?' + $p = $pv; + } else { + break; + } + } + $end = null; + $d = 0; + for ( $scan = $i + 1; $scan <= $close; $scan++ ) { + $d += struct_delta( $tokens[ $scan ] ); + if ( 0 === $d && 59 === $tokens[ $scan ][0] ) { + $end = $scan; + break; + } + } + if ( null === $end ) { + fail( 'property without terminating semicolon: ' . $t[1] ); + } + $members[] = array( + 'kind' => 'prop', 'name' => $t[1], 'start' => $p, 'end' => $end, + 'doc' => doc_start( $tokens, $p ), + 'open' => null, 'close' => null, 'vis' => null, + 'static' => false, 'final' => false, 'abstract' => false, + ); + $i = $end + 1; + continue; + } if ( T_CONST !== $id && T_FUNCTION !== $id ) { $i++; continue; @@ -798,16 +892,6 @@ function helper_bodies( string $absText ): array { return $out; } -function registration_stmt( array $tokens, array $stmts ): array { - foreach ( $stmts as $k => $st ) { - $f = stmt_start( $tokens, $st ); - if ( T_STRING === $tokens[$f][0] && 'wp_register_ability' === $tokens[$f][1] ) { - return array( $k, $f ); - } - } - fail( 'no wp_register_ability(...) statement found' ); -} - /* --------------------------------------------------------------------- * FORWARD transform * ------------------------------------------------------------------- */ @@ -840,6 +924,26 @@ function build_registration( string $nameLit, array $vals ): string { return $out; } +/** + * The guard condition of a should_register() return expression: the + * expression with its leading `!` negation removed, unwrapped from one + * outer pair of parentheses when they enclose all of it. + */ +function guard_condition( string $expr ): string { + $expr = trim( $expr ); + '!' === substr( $expr, 0, 1 ) || fail( 'should_register() must return a negated condition, `! `' ); + $cond = trim( substr( $expr, 1 ) ); + if ( '(' === substr( $cond, 0, 1 ) ) { + $tokens = tokenize_source( ' core class text. * @@ -852,12 +956,13 @@ function transform_forward( string $pkgText, string $absText ): string { $by = index_by_name( $members ); $abname = unquote( return_expr( $tokens, $by['ability_name'] ) ); - list( $dir, $pkgClass, $coreClass, $regMethod, $category ) = slug_parts( $abname ); + $prof = profile( $abname ); + list( $dir, $pkgClass, $coreClass, $regMethod ) = slug_parts( $abname ); if ( $cls['name'] !== $pkgClass ) { fail( 'unexpected class name ' . $cls['name'] . ' for ability ' . $abname . ' (expected ' . $pkgClass . ')' ); } - if ( isset( $by['register'] ) || isset( $by['register_content_query'] ) ) { - fail( 'package class must not declare register()/register_content_query()' ); + if ( isset( $by['register'] ) || isset( $by[ $regMethod ] ) ) { + fail( 'package class must not declare register()/' . $regMethod . '()' ); } foreach ( INLINE_HELPERS as $h ) { if ( isset( $by[ $h ] ) ) { @@ -879,13 +984,26 @@ function transform_forward( string $pkgText, string $absText ): string { if ( isset( $vals['required_capabilities'] ) && expr_is_empty_array( $vals['required_capabilities'] ) ) { unset( $vals['required_capabilities'] ); } + // A null permission callback means the required capabilities own authorization: core omits the entry. + if ( 'null' === strtolower( trim( $vals['permission_callback'] ) ) ) { + unset( $vals['permission_callback'] ); + } + + /* --- register() prologue and guard from prepare()/should_register() --- */ + $prepared = array(); + if ( isset( $by['prepare'] ) ) { + $pRec = $by['prepare']; + foreach ( body_statements( $tokens, $pRec['open'], $pRec['close'] ) as $st ) { + $prepared[] = stmt_text( $tokens, $st ); + } + } + $guard = isset( $by['should_register'] ) ? guard_condition( return_expr( $tokens, $by['should_register'] ) ) : null; - /* --- register_content_query() prologue from input_schema() ------------- */ + /* --- register_*() prologue from input_schema() ------------------------- */ $inRec = $by['input_schema']; $stmts = body_statements( $tokens, $inRec['open'], $inRec['close'] ); $assigns = array(); - $postTypesAt = -1; - $sawSpliceGuard = false; + $spliceAt = -1; foreach ( $stmts as $idx => $st ) { $f = stmt_start( $tokens, $st ); $id = $tokens[ $f ][0]; @@ -893,35 +1011,26 @@ function transform_forward( string $pkgText, string $absText ): string { continue; // the schema return itself becomes the registration entry } if ( T_IF === $id ) { - $sawSpliceGuard = true; - continue; + fail( 'input_schema() must not contain the void early-return splice' ); } if ( T_VARIABLE !== $id ) { fail( 'unexpected statement in input_schema(): ' . token_repr( $tokens[ $f ] ) ); } - if ( '$post_types' === $tokens[ $f ][1] ) { - $postTypesAt = count( $assigns ); + if ( null !== $prof['splice_after'] && $prof['splice_after'] === $tokens[ $f ][1] ) { + $spliceAt = count( $assigns ); } $assigns[] = $st; } - if ( $sawSpliceGuard ) { - fail( 'input_schema() must not contain the void early-return splice' ); - } - if ( $postTypesAt < 0 ) { - fail( 'input_schema() missing a $post_types assignment' ); - } - - $probe = array(); - foreach ( $assigns as $st ) { - $probe[] = stmt_text( $tokens, $st ); + if ( null !== $prof['splice_after'] && $spliceAt < 0 ) { + fail( 'input_schema() missing a ' . $prof['splice_after'] . ' assignment' ); } - /* --- assemble register_content_query() --------------------------------- */ + /* --- assemble register_*() --------------------------------------------- */ $regCq = "\tprivate function " . $regMethod . "(): void {\n"; foreach ( $assigns as $idx => $st ) { $regCq .= "\t\t" . stmt_text( $tokens, $st ) . "\n"; - if ( $postTypesAt === $idx ) { - $regCq .= "\t\tif ( empty( \$post_types ) ) {\n"; + if ( $spliceAt === $idx ) { + $regCq .= "\t\tif ( empty( " . $prof['splice_after'] . " ) ) {\n"; $regCq .= "\t\t\treturn;\n"; $regCq .= "\t\t}\n\n"; } @@ -929,28 +1038,35 @@ function transform_forward( string $pkgText, string $absText ): string { $regCq .= "\n" . build_registration( $nameLit, $vals ); $regCq .= "\t}\n"; + /* --- assemble register() ------------------------------------------------ */ $registerFn = "\t/**\n" - . "\t * Registers all content abilities.\n" + . "\t * " . $prof['register_doc'] . "\n" . "\t *\n" . "\t * Must run on the `wp_abilities_api_init` hook.\n" . "\t *\n" . "\t * @since 7.2.0\n" . "\t */\n" - . "\tpublic function register(): void {\n" - . "\t\t\$this->register_content_query();\n\n" - . "\t\t/*\n" - . "\t\t * Future write-oriented content abilities can be registered here, reusing\n" - . "\t\t * the shared helpers below (get_exposed_post_type(), format_post(),\n" - . "\t\t * check_permission()).\n" - . "\t\t */\n" - . "\t}\n"; - - /* --- verbatim constants and methods, with helper re-inline -------------- */ - $chunks = array(); - $pending = array(); - foreach ( HELPER_AFTER as $h => $anchor ) { - $pending[ $h ] = $anchor; + . "\tpublic function register(): void {\n"; + foreach ( $prepared as $line ) { + $registerFn .= "\t\t" . reindent( $line, 0 ) . "\n"; + } + if ( null !== $guard ) { + $registerFn .= "\t\tif ( " . $guard . " ) {\n" + . "\t\t\treturn;\n" + . "\t\t}\n\n"; } + $registerFn .= "\t\t\$this->" . $regMethod . "();\n"; + if ( array() !== $prof['register_note'] ) { + $registerFn .= "\n\t\t/*\n"; + foreach ( $prof['register_note'] as $line ) { + $registerFn .= "\t\t * " . $line . "\n"; + } + $registerFn .= "\t\t */\n"; + } + $registerFn .= "\t}\n"; + + /* --- verbatim constants, properties and methods, with helper re-inline -- */ + $pending = $prof['helpers']; $helpTexts = helper_texts( $absText ); $placeHelpers = static function ( string $anchor ) use ( &$methodChunks, &$pending, $helpTexts ) { @@ -971,6 +1087,7 @@ function transform_forward( string $pkgText, string $absText ): string { }; $constChunk = ''; + $propChunk = ''; $methodChunks = array(); foreach ( $members as $rec ) { $name = $rec['name']; @@ -978,7 +1095,11 @@ function transform_forward( string $pkgText, string $absText ): string { $constChunk .= "\t" . member_text( $tokens, $rec ) . "\n"; continue; } - if ( in_array( $name, AUTHORING_METHODS, true ) ) { + if ( 'prop' === $rec['kind'] ) { + $propChunk .= "\n\t" . member_text( $tokens, $rec ) . "\n"; + continue; + } + if ( in_array( $name, AUTHORING_METHODS, true ) || in_array( $name, OPTIONAL_METHODS, true ) ) { continue; // consumed by the registration rebuild } $methodChunks[] = "\t" . member_text( $tokens, $rec ) . "\n"; @@ -988,7 +1109,7 @@ function transform_forward( string $pkgText, string $absText ): string { fail( 'helpers without anchor in package order: ' . implode( ', ', array_keys( $pending ) ) ); } - $body = $constChunk . "\n" . $registerFn . "\n" . $regCq . "\n" . implode( "\n", $methodChunks ); + $body = $constChunk . $propChunk . "\n" . $registerFn . "\n" . $regCq . "\n" . implode( "\n", $methodChunks ); $header = " array(", "\t'name' => '" . $abname . "',", "\t'class' => '" . $dir . '\\' . $pkgClass . "',", - "\t'category' => '" . $category . "',", + "\t'category' => '" . $prof['category'] . "',", "\t'tier' => 'core',", "\t'min_wp_version' => '6.9',", "\t'core_since' => '7.2',", - "\t'requires' => array( 'show_in_abilities' ),", + "\t'requires' => array( " . implode( ', ', $requires ) . ' ),', "\t'renamed_from' => null,", - "\t'proposal' => 'https://github.com/WordPress/wordpress-develop/pull/12195',", + "\t'proposal' => '" . $prof['proposal'] . "',", "),", '', - 'Note: tier=core, core_since=7.2, requires=[show_in_abilities] per settled design.', - 'min_wp_version/proposal values are copied from the existing Manifest.php entry;', - 'WP2-flagged for human confirmation.', + 'Note: tier=core, core_since=7.2 per settled design; category, requires and', + 'proposal come from the coreify profile and must match src/Manifest.php.', ); return implode( "\n", $lines ); } +/** + * The core form's registration method: the register_*() member holding the + * wp_register_ability(...) statement. + * + * @return array{array,list,int} [member record, its statements, registration statement index] + */ +function core_registration_method( array $tokens, array $members ): array { + foreach ( $members as $rec ) { + if ( 'function' !== $rec['kind'] || 'register' === $rec['name'] || 0 !== strpos( $rec['name'], 'register_' ) || null === $rec['open'] ) { + continue; + } + $stmts = body_statements( $tokens, $rec['open'], $rec['close'] ); + foreach ( $stmts as $k => $st ) { + $f = stmt_start( $tokens, $st ); + if ( T_STRING === $tokens[ $f ][0] && 'wp_register_ability' === $tokens[ $f ][1] ) { + return array( $rec, $stmts, $k ); + } + } + } + fail( 'no register_*() method with a wp_register_ability(...) statement in core form' ); +} + +/** + * Parse core's register(): the state assignments before an optional void + * early-return guard, then the single call into the registration method. + * + * @return array{list,?string} [prepare() statement texts, guard condition or null] + */ +function parse_core_register( array $tokens, array $rec, string $regMethod ): array { + $prepared = array(); + $guard = null; + $called = false; + foreach ( body_statements( $tokens, $rec['open'], $rec['close'] ) as $st ) { + $f = stmt_start( $tokens, $st ); + $id = $tokens[ $f ][0]; + if ( $called ) { + fail( 'unexpected statement after $this->' . $regMethod . '() in register()' ); + } + if ( T_IF === $id ) { + null === $guard || fail( 'expected at most one early-return guard in register()' ); + $paren = next_meaningful_token( $tokens, $f + 1, $st[1] ); + $paren !== null && 40 === $tokens[ $paren ][0] || fail( 'register() guard without a condition' ); + $pclose = match_group( $tokens, $paren ); + $brace = next_meaningful_token( $tokens, $pclose + 1, $st[1] ); + $brace !== null && 123 === $tokens[ $brace ][0] || fail( 'register() guard without a block' ); + $body = array(); + foreach ( body_statements( $tokens, $brace, match_group( $tokens, $brace ) ) as $inner ) { + $body[] = stmt_text( $tokens, $inner ); + } + array( 'return;' ) === $body || fail( 'register() guard must only `return;`' ); + $guard = span_trim( $tokens, $paren + 1, $pclose - 1 ); + continue; + } + if ( T_VARIABLE === $id && '$this' === $tokens[ $f ][1] && '$this->' . $regMethod . '();' === preg_replace( '/\s+/', '', stmt_text( $tokens, $st ) ) ) { + $called = true; + continue; + } + if ( T_VARIABLE === $id && null === $guard ) { + $prepared[] = stmt_text( $tokens, $st ); + continue; + } + fail( 'unexpected statement in register(): ' . token_repr( $tokens[ $f ] ) ); + } + $called || fail( 'register() never calls $this->' . $regMethod . '()' ); + return array( $prepared, $guard ); +} + +/** Negate a guard condition for should_register(): `! cond`, parenthesized unless a single call. */ +function negate_condition( string $cond ): string { + $tokens = tokenize_source( ' package class text. */ @@ -1099,17 +1304,17 @@ function transform_reverse( string $coreText ): string { $cls = parse_class( $tokens ); $members = parse_members( $tokens, $cls['open'], $cls['close'] ); $by = index_by_name( $members ); - isset( $by['register_content_query'] ) || fail( 'no register_content_query() in core form' ); - - $cqRec = $by['register_content_query']; - $stmts = body_statements( $tokens, $cqRec['open'], $cqRec['close'] ); - list( $regIdx, $regTok ) = array_values( registration_stmt( $tokens, $stmts ) ); + list( $cqRec, $stmts, $regIdx ) = core_registration_method( $tokens, $members ); list( $abname, $entries ) = parse_registration( $tokens, $stmts[ $regIdx ] ); - list( $dir, $pkgClass, $coreClass, $regMethod, $category ) = slug_parts( $abname ); + $prof = profile( $abname ); + list( $dir, $pkgClass, $coreClass, $regMethod ) = slug_parts( $abname ); if ( $cls['name'] !== $coreClass ) { fail( 'core class name ' . $cls['name'] . ' does not match derived ' . $coreClass . ' for ' . $abname ); } + $cqRec['name'] === $regMethod || fail( 'registration method ' . $cqRec['name'] . '() does not match derived ' . $regMethod . '()' ); + isset( $by['register'] ) || fail( 'no register() in core form' ); + list( $prepared, $guard ) = parse_core_register( $tokens, $by['register'], $regMethod ); /* prologue assignments before wp_register_ability(...), splice dropped */ $guardCount = 0; @@ -1127,7 +1332,8 @@ function transform_reverse( string $coreText ): string { } fail( 'unexpected statement before wp_register_ability(): ' . token_repr( $tokens[ $f ] ) ); } - 1 === $guardCount || fail( 'expected exactly one void early-return guard, found ' . $guardCount ); + $expectGuards = null === $prof['splice_after'] ? 0 : 1; + $expectGuards === $guardCount || fail( 'expected ' . $expectGuards . ' void early-return guard(s) in ' . $regMethod . '(), found ' . $guardCount ); /* helper drop with body-equality guard */ $absPath = default_abstract_path(); @@ -1135,6 +1341,7 @@ function transform_reverse( string $coreText ): string { /* authoring method bodies */ $authors = array(); + $types = AUTHORING_TYPES; $nameLit = "'" . $abname . "'"; $authors['ability_name'] = 'return ' . $nameLit . ';'; @@ -1147,7 +1354,14 @@ function transform_reverse( string $coreText ): string { $authors['category_slug'] = $mkret( 'category' ); $authors['output_schema'] = $mkret( 'output_schema' ); $authors['make_execute_callback'] = $mkret( 'execute_callback' ); - $authors['make_permission_callback'] = $mkret( 'permission_callback' ); + if ( isset( $entries['permission_callback'] ) ) { + $authors['make_permission_callback'] = $mkret( 'permission_callback' ); + } else { + // Core omits the callback when the required capabilities own authorization. + isset( $entries['required_capabilities'] ) || fail( 'registration has neither permission_callback nor required_capabilities' ); + $authors['make_permission_callback'] = 'return null;'; + $types['make_permission_callback'] = '?callable'; + } $authors['ability_meta'] = $mkret( 'meta' ); $rc = 'return array();'; @@ -1162,8 +1376,24 @@ function transform_reverse( string $coreText ): string { } $authors['input_schema'] = $prologue . "\t\t" . 'return ' . reindent( $entries['input_schema'] ?? '', -2 ) . ';' . "\n"; + /* optional authoring methods from core's register() */ + $optional = array(); + if ( array() !== $prepared ) { + $optional['prepare'] = array( + 'sig' => 'protected function prepare(): void', + 'doc' => 'Computes the state core computes in register() before registering.', + 'body' => "\t\t" . implode( "\n\t\t", $prepared ), + ); + } + if ( null !== $guard ) { + $optional['should_register'] = array( + 'sig' => 'public function should_register(): bool', + 'doc' => 'Whether core registers the ability, the negation of its register() early return.', + 'body' => "\t\treturn " . negate_condition( $guard ) . ';', + ); + } + /* assemble */ - $nsParts = array( $dir, $pkgClass ); $out = "core token transform for wordpress/abilities. Usage: - php coreify.php [--in ] [--out ] - php coreify.php --reverse [--in ] [--out ] - php coreify.php --check [--in ] [--abs ] + php coreify.php [--ability ] [--in ] [--out ] + php coreify.php --reverse [--ability ] [--in ] [--out ] + php coreify.php --check [--ability ] [--in ] [--pkg ] [--abs ] php coreify.php --help +Abilities with a transform profile: core/content-query, core/settings-get. + Modes: - (default) forward: package -> core form. Input defaults to - src/Content/Content_Query.php. Writes the fixture-shaped class - to tools/out/class-wp-abilities-content.php (unless --out). + (default) forward: package -> core form. Input defaults to the ability's + package file (src/Content/Content_Query.php for the default + core/content-query). Writes the fixture-shaped class to + tools/out/class-wp-abilities-.php (unless --out). --reverse core -> package form (+ manifest entry skeleton on stdout). - Input defaults to the trunk fixture - tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php. - Writes tools/out/Content/Content_Query.php (unless --out). + Input defaults to the ability's trunk fixture under + tests/Fixtures/abilities-api/abilities/. Writes + tools/out//.php (unless --out). --check acceptance gate: reverse(fixture) -> forward() -> semantic token diff vs the ORIGINAL fixture (hard gate, prints first mismatch). - Also diffs the reverse output vs the hand-port - src/Content/Content_Query.php. Exits non-zero on divergence. + Also diffs the reverse output vs the hand-port package file. + Runs every profiled ability unless --ability is given. Exits + non-zero on divergence. Options: - --in input file (per-mode default as above; the same path serves - as the fixture input for --check and reverse) - --out output file (default tools/out/...) - --abs path to src/Abstract_Core_Ability.php (default derived from - the repo root) - --pkg --check only: package reference file for the second diff - (default src/Content/Content_Query.php) - --help this help + --ability the profiled ability whose default paths to use + (default core/content-query; --check: all) + --in input file (per-mode default as above; the same path serves + as the fixture input for --check and reverse) + --out output file (default tools/out/...) + --abs path to src/Abstract_Core_Ability.php (default derived from + the repo root) + --pkg --check only: package reference file for the second diff + (default the ability's package file) + --help this help Exit codes: 0 success; 1 transform/semantic-diff failure; 2 usage error. TXT; @@ -1286,6 +1536,7 @@ function usage(): void { function parse_args( array $argv ): array { $o = array( 'mode' => 'forward', + 'ability' => null, 'in' => null, 'out' => null, 'abs' => null, @@ -1306,6 +1557,10 @@ function parse_args( array $argv ): array { case $arg === '-h': $o['help'] = true; break; + case $arg === '--ability': + $o['ability'] = $argv[ ++$i ] ?? fail( '--ability requires a name' ); + profile( $o['ability'] ); + break; case $arg === '--in': $o['in'] = $argv[ ++$i ] ?? fail( '--in requires a path' ); break; @@ -1346,53 +1601,30 @@ function write_out( string $path, string $text ): void { echo '[coreify] wrote ' . $path . " (" . strlen( $text ) . " bytes)\n"; } -function run( array $o ): int { - $root = default_root(); - $absPath = $o['abs'] ?? default_abstract_path(); - - if ( 'forward' === $o['mode'] ) { - $in = $o['in'] ?? $root . '/src/Content/Content_Query.php'; - $out = $o['out'] ?? $root . '/tools/out/class-wp-abilities-content.php'; - $result = transform_forward( read_file( $in ), read_file( $absPath ) ); - write_out( $out, $result ); - echo "[coreify] forward OK: {$in} -> {$out}\n"; - return 0; - } - - if ( 'reverse' === $o['mode'] ) { - $in = $o['in'] ?? $root . '/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php'; - $coreText = read_file( $in ); - $result = transform_reverse( $coreText ); - $abname = reverse_ability_name( $coreText ); - $dir = slug_parts( $abname ) ? slug_parts( $abname )[0] : ''; - $defaultOut = $root . '/tools/out/' . ( $dir ?: 'Content' ) . '/Content_Query.php'; - $out = $o['out'] ?? $defaultOut; - write_out( $out, $result ); - echo "[coreify] reverse OK: {$in} -> {$out}\n"; - echo build_manifest( $abname ) . "\n"; - return 0; - } +/** Default tools/out paths of an ability: [reverse (package form), forward (core form)]. */ +function out_paths( string $root, string $abname ): array { + list( $dir, $pkgClass, $coreClass ) = slug_parts( $abname ); + return array( + $root . '/tools/out/' . $dir . '/' . $pkgClass . '.php', + $root . '/tools/out/class-' . str_replace( '_', '-', strtolower( $coreClass ) ) . '.php', + ); +} - /* --- check -------------------------------------------------------------- */ - $in = $o['in'] ?? $root . '/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php'; - $pkgPath = $o['pkg'] ?? $root . '/src/Content/Content_Query.php'; +/** Round-trip check of one fixture/package pair. */ +function check_pair( string $root, string $in, string $pkgPath, string $absText ): bool { $fixture = read_file( $in ); $handport = read_file( $pkgPath ); - $absText = read_file( $absPath ); - - $revOut = $root . '/tools/out/Content/Content_Query.php'; - $fwdOut = $root . '/tools/out/class-wp-abilities-content.php'; + list( $revOut, $fwdOut ) = out_paths( $root, reverse_ability_name( $fixture ) ); $pkgText = transform_reverse( $fixture ); write_out( $revOut, $pkgText ); $coreText = transform_forward( $pkgText, $absText ); write_out( $fwdOut, $coreText ); - $okA = true; - $okB = true; + $ok = true; $mA = semdiff( $coreText, $fixture ); if ( null !== $mA ) { - $okA = false; + $ok = false; fwrite( STDERR, "[check] FAIL: round-trip forward output vs ORIGINAL fixture\n" ); print_mismatch( 'roundtrip-vs-fixture', $mA ); } else { @@ -1400,30 +1632,65 @@ function run( array $o ): int { } $mB = semdiff( $pkgText, $handport ); if ( null !== $mB ) { - $okB = false; + $ok = false; fwrite( STDERR, "[check] FAIL: reverse output vs hand-port package file\n" ); print_mismatch( 'reverse-vs-handport', $mB ); } else { echo "[check] PASS: reverse output vs hand-port package file (0 semantic differences)\n"; } - if ( ! $okA || ! $okB ) { + return $ok; +} + +function run( array $o ): int { + $root = default_root(); + $absPath = $o['abs'] ?? default_abstract_path(); + $abname = $o['ability'] ?? DEFAULT_ABILITY; + $prof = profile( $abname ); + + if ( 'forward' === $o['mode'] ) { + $in = $o['in'] ?? $root . '/' . $prof['package']; + $result = transform_forward( read_file( $in ), read_file( $absPath ) ); + $out = $o['out'] ?? out_paths( $root, $abname )[1]; + write_out( $out, $result ); + echo "[coreify] forward OK: {$in} -> {$out}\n"; + return 0; + } + + if ( 'reverse' === $o['mode'] ) { + $in = $o['in'] ?? $root . '/' . $prof['fixture']; + $coreText = read_file( $in ); + $result = transform_reverse( $coreText ); + $abname = reverse_ability_name( $coreText ); + $out = $o['out'] ?? out_paths( $root, $abname )[0]; + write_out( $out, $result ); + echo "[coreify] reverse OK: {$in} -> {$out}\n"; + echo build_manifest( $abname ) . "\n"; + return 0; + } + + /* --- check -------------------------------------------------------------- */ + $absText = read_file( $absPath ); + $names = ( null === $o['ability'] && null === $o['in'] && null === $o['pkg'] ) ? array_keys( PROFILES ) : array( $abname ); + $ok = true; + foreach ( $names as $name ) { + $p = profile( $name ); + echo "[check] {$name}\n"; + $ok = check_pair( $root, $o['in'] ?? $root . '/' . $p['fixture'], $o['pkg'] ?? $root . '/' . $p['package'], $absText ) && $ok; + } + if ( ! $ok ) { return 1; } echo "[check] OK: round-trip invariant holds.\n"; return 0; } -/** Ability name alone (for default reverse out path). */ +/** Ability name alone (for default out paths). */ function reverse_ability_name( string $coreText ): string { $tokens = tokenize_source( $coreText ); $cls = parse_class( $tokens ); $members = parse_members( $tokens, $cls['open'], $cls['close'] ); - $by = index_by_name( $members ); - isset( $by['register_content_query'] ) || fail( 'no register_content_query() in core form' ); - $rec = $by['register_content_query']; - $stmts = body_statements( $tokens, $rec['open'], $rec['close'] ); - list( $idx ) = registration_stmt( $tokens, $stmts ); - list( $abname, $entries ) = parse_registration( $tokens, $stmts[ $idx ] ); + list( , $stmts, $idx ) = core_registration_method( $tokens, $members ); + list( $abname ) = parse_registration( $tokens, $stmts[ $idx ] ); return $abname; } From 2582b6751a3c27ab4eb0fe541c72729c1ec18227 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 10:39:29 -0600 Subject: [PATCH 10/14] Bring back trimmed code comments as those come from Core --- src/Settings/Settings_Get.php | 36 +++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/src/Settings/Settings_Get.php b/src/Settings/Settings_Get.php index bb99a7c..3dd79b6 100644 --- a/src/Settings/Settings_Get.php +++ b/src/Settings/Settings_Get.php @@ -26,7 +26,7 @@ final class Settings_Get extends Abstract_Core_Ability { /** * The ability category used for settings abilities. * - * @since x.x.x + * @since 7.2.0 * @var string */ private const CATEGORY = 'site'; @@ -34,7 +34,7 @@ final class Settings_Get extends Abstract_Core_Ability { /** * Settings exposed through the Abilities API, computed once at registration. * - * @since x.x.x + * @since 7.2.0 * @var array}> */ private $exposed_settings = array(); @@ -161,7 +161,7 @@ public function should_register(): bool { /** * Executes the `core/settings-get` ability. * - * @since x.x.x + * @since 7.2.0 * * @param mixed $input Optional. The ability input. Default empty array. * @return array Map of exposed setting name to current value. @@ -218,7 +218,10 @@ private function execute_settings_get( $input = array() ): array { /** * Builds the input schema for the `core/settings-get` ability: optional filters by group and/or name. * - * @since x.x.x + * Both `group` and `fields` are optional; supplying both narrows the response to their + * intersection, and supplying neither returns every exposed setting. + * + * @since 7.2.0 * * @param list $groups Available settings groups. * @param list $field_names Available exposed setting names. @@ -251,7 +254,10 @@ private function get_settings_get_input_schema( array $groups, array $field_name /** * Builds the output schema for the `core/settings-get` ability. * - * @since x.x.x + * No setting is marked required because the `group` and `fields` inputs let the caller + * request any subset, and a setting whose value does not match its schema is left out. + * + * @since 7.2.0 * * @return array The output JSON Schema. */ @@ -267,7 +273,14 @@ private function get_settings_get_output_schema(): array { /** * Returns the settings exposed through the Abilities API. * - * @since x.x.x + * Reads {@see get_registered_settings()} and keeps only settings flagged with a truthy + * `show_in_abilities` argument, of a type the settings endpoint supports. Each entry is + * keyed by its exposed name and carries the underlying option name, the settings group, + * the registered default (null when there is none), and a JSON Schema describing the value. + * + * Two settings exposed under the same name trigger a notice, and the later one is exposed. + * + * @since 7.2.0 * * @return array}> Settings keyed by exposed name. */ @@ -317,7 +330,11 @@ private function get_exposed_settings(): array { /** * Returns the name and schema overrides used to expose a setting to abilities. * - * @since x.x.x + * When `show_in_abilities` is `true`, the setting is exposed the same way as in the + * REST API: it uses the `name` and `schema` from `show_in_rest`. An array is used + * as is. + * + * @since 7.2.0 * * @param array $args The setting registration arguments. * @return array The exposure arguments, with optional `name` and `schema` keys. @@ -333,7 +350,10 @@ private function get_exposure_args( array $args ): array { /** * Builds the JSON Schema describing a single setting's value. * - * @since x.x.x + * As in the settings endpoint, objects in the schema reject properties they do not declare, + * unless the schema allows them. + * + * @since 7.2.0 * * @param array $args The setting registration arguments. * @param array $show The exposure arguments, see get_exposure_args(). From cc74f271e1b02769d696447e8fe8ef51cde7d062 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 11:00:44 -0600 Subject: [PATCH 11/14] Ensure settings match latest trunk changes --- .../polyfills/setting-show-in-abilities.php | 74 +++++++++++-------- 1 file changed, 44 insertions(+), 30 deletions(-) diff --git a/src/Support/polyfills/setting-show-in-abilities.php b/src/Support/polyfills/setting-show-in-abilities.php index 6871b0b..d437e2a 100644 --- a/src/Support/polyfills/setting-show-in-abilities.php +++ b/src/Support/polyfills/setting-show-in-abilities.php @@ -18,6 +18,11 @@ * trunk. This polyfill injects that same default through the * `register_setting_args` filter, and catches up the ones registered before * it loaded. + * - Trunk also rewrote the `siteurl` description in 7.2. The polyfill gives + * that setting an equivalent `show_in_abilities` array instead of `true`, + * carrying trunk's description, so the ability's schema matches trunk while + * the host's own registration, and its REST settings schema, stay as they + * are. * - Trunk registers `wp_page_for_privacy_policy` in register_initial_settings() * since 7.2, exposed as `page_for_privacy_policy`. Older hosts do not * register it at all, so the polyfill registers it for abilities only: @@ -26,11 +31,12 @@ * in trunk's place among the registered settings. * - Core registers its initial settings on `rest_api_init`, which fires * lazily and independently of `wp_abilities_api_init`. Trunk registers them - * early through _wp_register_initial_settings_for_abilities(), restoring - * `$new_allowed_options` so the options screens are not affected. This - * polyfill does the same when it loads, which is during - * `wp_abilities_api_init`, before the requiring ability takes its - * exposed-settings snapshot. + * early through _wp_register_initial_settings_for_abilities(), at priority 1 + * of `wp_abilities_api_init`, restoring `$new_allowed_options` so the + * options screens are not affected. This polyfill does the same when it + * loads, which for a deferred registration is that same priority (see + * Registrar::queue_feature_preloads()), before the requiring ability takes + * its exposed-settings snapshot. * * Loading: through require_once, only from the Registrar (via * Support\Features) when an ability requires the feature and core lacks it. @@ -47,34 +53,42 @@ /** * The settings trunk's register_initial_settings() flags with - * `show_in_abilities`, keyed by option name, in trunk's order. + * `show_in_abilities`, keyed by option name, in trunk's order, each with the + * `show_in_abilities` value the polyfill gives it. * * Keep in sync with trunk when a fixture refresh changes the list. */ $wordpress_abilities_exposed_core_settings = array( // General. - 'blogname', - 'blogdescription', - 'siteurl', - 'admin_email', - 'timezone_string', - 'date_format', - 'time_format', - 'start_of_week', - 'WPLANG', + 'blogname' => true, + 'blogdescription' => true, + // Trunk's 7.2 description; the host's show_in_rest name and schema, restated. + 'siteurl' => array( + 'name' => 'url', + 'schema' => array( + 'format' => 'uri', + 'description' => __( 'The URL where WordPress core files are served. May differ from the public site URL.' ), + ), + ), + 'admin_email' => true, + 'timezone_string' => true, + 'date_format' => true, + 'time_format' => true, + 'start_of_week' => true, + 'WPLANG' => true, // Writing. - 'use_smilies', - 'default_category', - 'default_post_format', + 'use_smilies' => true, + 'default_category' => true, + 'default_post_format' => true, // Reading. - 'posts_per_page', - 'show_on_front', - 'page_on_front', - 'page_for_posts', - 'wp_page_for_privacy_policy', + 'posts_per_page' => true, + 'show_on_front' => true, + 'page_on_front' => true, + 'page_for_posts' => true, + 'wp_page_for_privacy_policy' => true, // Discussion. - 'default_ping_status', - 'default_comment_status', + 'default_ping_status' => true, + 'default_comment_status' => true, ); /** @@ -94,8 +108,8 @@ return $args; } - if ( in_array( $option_name, $wordpress_abilities_exposed_core_settings, true ) ) { - $args['show_in_abilities'] = true; + if ( isset( $wordpress_abilities_exposed_core_settings[ $option_name ] ) ) { + $args['show_in_abilities'] = $wordpress_abilities_exposed_core_settings[ $option_name ]; } return $args; @@ -110,14 +124,14 @@ * the registered setting is never overridden. */ if ( isset( $GLOBALS['wp_registered_settings'] ) && is_array( $GLOBALS['wp_registered_settings'] ) ) { - foreach ( $wordpress_abilities_exposed_core_settings as $polyfill_option_name ) { + foreach ( $wordpress_abilities_exposed_core_settings as $polyfill_option_name => $polyfill_show ) { if ( isset( $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) && is_array( $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) && ! array_key_exists( 'show_in_abilities', $GLOBALS['wp_registered_settings'][ $polyfill_option_name ] ) ) { - $GLOBALS['wp_registered_settings'][ $polyfill_option_name ]['show_in_abilities'] = true; + $GLOBALS['wp_registered_settings'][ $polyfill_option_name ]['show_in_abilities'] = $polyfill_show; } } - unset( $polyfill_option_name ); + unset( $polyfill_option_name, $polyfill_show ); } unset( $wordpress_abilities_exposed_core_settings ); From ff260da7614fc02c286d00ff5acf26b49273420d Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 11:01:09 -0600 Subject: [PATCH 12/14] Update tests --- tests/Abilities/SettingsGetTest.php | 9 +++++ tests/RegistrarTest.php | 61 ++++++++++++++++++++++++++--- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/tests/Abilities/SettingsGetTest.php b/tests/Abilities/SettingsGetTest.php index 33d2ebe..b0cdde7 100644 --- a/tests/Abilities/SettingsGetTest.php +++ b/tests/Abilities/SettingsGetTest.php @@ -272,6 +272,15 @@ public function test_schemas_expose_trunk_core_settings(): void { self::assertSame( array( 'open', 'closed' ), $output['properties']['default_comment_status']['enum'] ); self::assertSame( 'email', $output['properties']['email']['format'] ); self::assertSame( 'integer', $output['properties']['page_for_privacy_policy']['type'] ); + self::assertSame( + array( + 'type' => 'string', + 'description' => 'The URL where WordPress core files are served. May differ from the public site URL.', + 'format' => 'uri', + ), + $output['properties']['url'], + "Trunk's 7.2 siteurl schema, key order included." + ); } /** diff --git a/tests/RegistrarTest.php b/tests/RegistrarTest.php index d33bc44..47cf617 100644 --- a/tests/RegistrarTest.php +++ b/tests/RegistrarTest.php @@ -782,11 +782,9 @@ static function (): void { self::assertTrue( wp_has_ability( 'core/content-create' ), 'P8: restored — the manifest abilities register again for the following suites.' ); // The restored boot must have registered quietly from the Registrar's - // side: no Gate-8 rejection, no category complaints. The host API's - // own constructor notices for the re-instantiated abilities are - // tolerated pre-existing host noise (the pre-7.2 WP_Ability does not - // accept the core-landing-ready `required_capabilities` argument; - // trunk's does). + // side: no Gate-8 rejection, no category complaints. Only the + // Registrar's own traffic is asserted here; the abilities' own + // construction is covered by SettingsGetTest. $registrar_traffic = array_intersect_key( self::$wrong_usage, array_fill_keys( @@ -1011,5 +1009,58 @@ public function should_register(): bool { self::assertFalse( self::try_register_entry( 'test/registrar-declining', $entry ), 'A declining ability is skipped.' ); self::assertFalse( wp_has_ability( 'test/registrar-declining' ), 'A declining ability never reaches the registry.' ); self::assert_no_wrong_usage( 'The readiness skip is silent.' ); + + $overrides = new ReflectionMethod( Registrar::class, 'overrides_readiness' ); + $overrides->setAccessible( true ); // No-op on PHP 8.1+, required on 7.4. + self::assertTrue( $overrides->invoke( null, get_class( $declining ) ), 'A class declaring should_register() is probed.' ); + self::assertFalse( $overrides->invoke( null, Manifest::get( 'core/content-query' )['class'] ), 'A class keeping the default is not probed.' ); + } + + /** + * 11. Deferred registrations preload their support features at priority 1 + * of `wp_abilities_api_init`, where core prepares its own support surface + * on 7.2+, so a site's changes at priorities 2-9 are not undone. + */ + public function test_deferred_registration_preloads_features_at_priority_one(): void { + $preload_hooked = new ReflectionProperty( Registrar::class, 'preload_hooked' ); + $preloads = new ReflectionProperty( Registrar::class, 'preloads' ); + $preload_hooked->setAccessible( true ); // No-op on PHP 8.1+, required on 7.4. + $preloads->setAccessible( true ); + + self::open_fresh_init_window(); + $preload_hooked->setValue( null, false ); + $preloads->setValue( null, array() ); + + $hook = $GLOBALS['wp_filter']['wp_abilities_api_init'] ?? null; + $before = $hook ? count( $hook->callbacks[1] ?? array() ) : 0; + + $vetoed = static function ( string $name ): bool { + return 'core/content-create' !== $name; + }; + Registrar::register_all( array( 'filter' => $vetoed ) ); + Registrar::register( 'core/settings-get' ); + + self::assertCount( $before + 1, $GLOBALS['wp_filter']['wp_abilities_api_init']->callbacks[1], 'One preload callback is queued at priority 1.' ); + self::assertSame( Manifest::names(), array_keys( $preloads->getValue() ), 'Every deferred name is queued once.' ); + self::assertSame( array( 'filter' => $vetoed ), $preloads->getValue()['core/settings-get'], 'The first queued selection policy is kept.' ); + + self::reset_wrong_usage(); + self::silence_notices( + static function (): void { + WP_Abilities_Registry::get_instance(); // Re-fires wp_abilities_api_init: preload, then the deferred registrations. + } + ); + self::assertTrue( wp_has_ability( 'core/settings-get' ), 'The deferred registration runs after the preload.' ); + + // Restore the settled registry for the following suites. + self::open_fresh_init_window(); + Registrar::register_all(); + self::silence_notices( + static function (): void { + WP_Abilities_Registry::get_instance(); + } + ); + self::assertTrue( wp_has_ability( 'core/content-create' ), 'Restored: the manifest abilities register again for the following suites.' ); + self::reset_wrong_usage(); } } From 5fabe513b266b8442df8ed70f46eb45a6c59bbb0 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 11:01:50 -0600 Subject: [PATCH 13/14] Move new stub to it's own file --- .stubs/abilities-api.php | 29 +------------------------- .stubs/option.php | 44 ++++++++++++++++++++++++++++++++++++++++ phpstan.neon.dist | 2 ++ 3 files changed, 47 insertions(+), 28 deletions(-) create mode 100644 .stubs/option.php diff --git a/.stubs/abilities-api.php b/.stubs/abilities-api.php index 3b26b9f..267d88d 100644 --- a/.stubs/abilities-api.php +++ b/.stubs/abilities-api.php @@ -11,9 +11,7 @@ * 6.9 ( wordpress-develop trunk as of 2026-10-20: WP_Ability, * WP_Abilities_Registry, WP_Ability_Categories_Registry, * WP_Ability_Category, and the global API functions; the former test - * fixture shim files these were once mirrored against are removed), plus - * the 7.2 shape of get_registered_settings(), which the API's settings - * abilities read. + * fixture shim files these were once mirrored against are removed). * Once phpstan-wordpress ships Abilities API stubs, delete this file and its * stubFiles entry. * @@ -194,29 +192,4 @@ function wp_register_ability_category( string $slug, array $args ) { function wp_has_ability_category( string $slug ) { return false; } - - /** - * Retrieves an array of registered settings. - * - * Overrides the phpstan-wordpress shape, which predates 7.2: trunk's registered - * setting data adds the `show_in_abilities` argument, and the `group` and `default` - * keys are not always present. Mirrors trunk's wp-includes/option.php docblock. - * - * @since 4.7.0 - * @since 7.2.0 Registered setting data includes the `show_in_abilities` argument. - * - * @phpstan-return array, - * show_in_abilities?: bool|array, - * default?: mixed, - * }> - */ - function get_registered_settings() { - return array(); - } } diff --git a/.stubs/option.php b/.stubs/option.php new file mode 100644 index 0000000..16a4286 --- /dev/null +++ b/.stubs/option.php @@ -0,0 +1,44 @@ +, + * show_in_abilities?: bool|array, + * default?: mixed, + * }> + */ + function get_registered_settings() { + return array(); + } +} diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 4152c70..c6edd2e 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -12,3 +12,5 @@ parameters: stubFiles: # Abilities API symbols (new in core trunk, not yet in phpstan-wordpress). - .stubs/abilities-api.php + # get_registered_settings() as of 7.2 (phpstan-wordpress predates `show_in_abilities`). + - .stubs/option.php From e5571a3113b881c4823e0a11388947071537b6a3 Mon Sep 17 00:00:00 2001 From: Darin Kotter Date: Fri, 23 Oct 2026 11:03:43 -0600 Subject: [PATCH 14/14] Ensure we load at priority 1 so others that hook in don't overwrite out changes. Change load behavior a bit to be more efficient --- KNOWN-ISSUES.md | 16 +++-- src/Registrar.php | 159 +++++++++++++++++++++++++++++++++++++--------- 2 files changed, 137 insertions(+), 38 deletions(-) diff --git a/KNOWN-ISSUES.md b/KNOWN-ISSUES.md index 8ac8c77..a2162d7 100644 --- a/KNOWN-ISSUES.md +++ b/KNOWN-ISSUES.md @@ -10,13 +10,15 @@ archive of resolved entries. ## Readiness probe constructs the ability twice -The Registrar reads `should_register()` on a probe instance before the -registry builds its own, so an ability with registration-time state computes -it twice per registration. For `core/settings-get` this is the -exposed-settings snapshot: both snapshots are identical, but a duplicate -exposed setting name fires its `_doing_it_wrong()` notice once per snapshot -(twice, where core fires once). The registry's `ability_class` mechanism -gives no way to hand it the probed instance. +For an ability that overrides `should_register()`, or under `public_only` +selection, the Registrar's Gate 7 reads a probe instance before the registry +builds its own, so an ability with registration-time state computes it +twice per registration. For `core/settings-get` this is the exposed-settings +snapshot: both snapshots are identical, but a duplicate exposed setting name +fires its `_doing_it_wrong()` notice once per snapshot (twice, where core +fires once). The registry's `ability_class` mechanism gives no way to hand +it the probed instance. Abilities that keep the default `should_register()` +are not probed outside `public_only`. ## Ported-as-is PR behaviors (documented, not fixed) diff --git a/src/Registrar.php b/src/Registrar.php index 3939fb1..0585dca 100644 --- a/src/Registrar.php +++ b/src/Registrar.php @@ -8,6 +8,7 @@ namespace WordPress\Abilities; +use ReflectionMethod; use WordPress\Abilities\Support\Features; /** @@ -74,6 +75,20 @@ final class Registrar { */ private static $deferred = array(); + /** + * Whether the support-feature preload hook was already queued. + * + * @var bool + */ + private static $preload_hooked = false; + + /** + * Deferred registrations whose support features to preload: name => selection policy. + * + * @var array> + */ + private static $preloads = array(); + /** * Static-only class. */ @@ -136,6 +151,8 @@ public static function register_all( array $args = array() ): void { return; } + self::queue_feature_preloads( Manifest::names(), $args ); + if ( self::$hooked ) { return; } @@ -195,6 +212,8 @@ public static function register( string $name, array $args = array() ): bool { return self::try_register( $name, $entry, $args ); } + self::queue_feature_preloads( array( $name ), $args ); + if ( isset( self::$deferred[ $name ] ) ) { return false; } @@ -243,6 +262,60 @@ private static function register_eligible( array $args ): void { } } + /** + * Queues the support-feature preload for deferred registrations. + * + * Core prepares its support surface at priority 1 of + * `wp_abilities_api_init`, before it registers its abilities at the + * default priority. The polyfills mirror that timing, so a + * site's own changes at priorities 2-9, such as unregistering a core + * setting, are not undone when the deferred registration loads them. + * + * @param list $names The manifest ability names being deferred. + * @param array $args Consumer-side selection policy, see register_all(). + * @return void + */ + private static function queue_feature_preloads( array $names, array $args ): void { + foreach ( $names as $name ) { + if ( ! isset( self::$preloads[ $name ] ) ) { + self::$preloads[ $name ] = $args; + } + } + + if ( self::$preload_hooked ) { + return; + } + self::$preload_hooked = true; + + add_action( + 'wp_abilities_api_init', + static function (): void { + self::preload_features(); + }, + 1 + ); + } + + /** + * Loads the polyfills of the queued abilities the selection policy keeps. + * + * @return void + */ + private static function preload_features(): void { + foreach ( self::$preloads as $name => $args ) { + $entry = Manifest::get( $name ); + if ( null === $entry || ! self::passes_selection( $name, $entry, $args ) ) { + continue; + } + + foreach ( (array) $entry['requires'] as $feature ) { + if ( ! Features::is_available( $feature ) ) { + Features::load_polyfill( $feature ); + } + } + } + } + /** * Queues the Registrar-owned declarations of the manifest-declared ability * categories. @@ -373,12 +446,14 @@ private static function declare_categories(): void { * class that the manifest knows simply registers nothing. * 4. Consumer `filter` selection policy. * 5. WordPress version vs. the entry's min_wp_version support floor. - * 6. `public_only`: probe the ability's own `public` meta. - * 7. Host readiness: every support-surface `requires` feature must be - * available, attempting a polyfill load when one exists; then the - * ability's own should_register() must agree, read on a probe - * instance once those features are in place (core's register() - * early return, e.g. nothing to expose). + * 6. Support-surface `requires`: every feature must be available, + * attempting a polyfill load when one exists (already loaded at + * priority 1 for deferred registrations, see queue_feature_preloads()). + * 7. One probe instance, built once those features are in place and only + * when something reads it: `public_only` checks the ability's own + * `public` meta, and an ability that overrides should_register() + * must agree to be registered (core's register() early return, e.g. + * nothing to expose). * 8. Registration via the core `ability_class` mechanism, merging * provenance meta (stability tier, renamed_from lineage). A null * result from core when the ability's manifest-declared category is @@ -405,43 +480,30 @@ private static function try_register( string $name, array $entry, array $args ): return true; } - // Gate 3: the class must be loadable (version-skew awareness). - if ( ! class_exists( $entry['class'] ) ) { + // Gates 3-5: loadable class, consumer selection, support floor. + if ( ! self::passes_selection( $name, $entry, $args ) ) { return false; } - // Gate 4: consumer selection policy. - $filter = isset( $args['filter'] ) && is_callable( $args['filter'] ) ? $args['filter'] : null; - if ( null !== $filter && ! (bool) $filter( $name, $entry ) ) { - return false; - } - - // Gate 5: package support floor. - if ( version_compare( get_bloginfo( 'version' ), $entry['min_wp_version'], '<' ) ) { - return false; + // Gate 6: support-surface features, with polyfill attempt. + foreach ( (array) $entry['requires'] as $feature ) { + if ( ! Features::is_available( $feature ) && ! Features::load_polyfill( $feature ) ) { + return false; + } } - // Gate 6: public-only selection probes the ability's own meta. - if ( ! empty( $args['public_only'] ) ) { + // Gate 7: a single probe, for public-only selection and readiness. + $public_only = ! empty( $args['public_only'] ); + if ( $public_only || self::overrides_readiness( $entry['class'] ) ) { $probe = new $entry['class'](); - if ( true !== $probe->get_meta_item( 'public', false ) ) { + if ( $public_only && true !== $probe->get_meta_item( 'public', false ) ) { return false; } - } - - // Gate 7: support-surface features, with polyfill attempt, then the - // ability's own registration-time readiness. - foreach ( (array) $entry['requires'] as $feature ) { - if ( ! Features::is_available( $feature ) && ! Features::load_polyfill( $feature ) ) { + if ( ! $probe->should_register() ) { return false; } } - $probe = new $entry['class'](); - if ( ! $probe->should_register() ) { - return false; - } - // Gate 8: register via the core `ability_class` mechanism, merging // provenance meta (stability, lineage). $meta = array( @@ -498,4 +560,39 @@ private static function try_register( string $name, array $entry, array $args ): return true; } + + /** + * Gates 3-5: the selection checks that need no ability instance. + * + * 3. The ability class must be loadable. + * 4. Consumer `filter` selection policy. + * 5. WordPress version vs. the entry's min_wp_version support floor. + * + * @param string $name The ability name. + * @param array $entry The manifest entry. + * @param array $args Consumer-side selection policy. + * @return bool Whether the ability passes all three. + */ + private static function passes_selection( string $name, array $entry, array $args ): bool { + if ( ! class_exists( $entry['class'] ) ) { + return false; + } + + $filter = isset( $args['filter'] ) && is_callable( $args['filter'] ) ? $args['filter'] : null; + if ( null !== $filter && ! (bool) $filter( $name, $entry ) ) { + return false; + } + + return version_compare( get_bloginfo( 'version' ), $entry['min_wp_version'], '>=' ); + } + + /** + * Whether an ability class overrides Abstract_Core_Ability::should_register(). + * + * @param class-string $ability_class The ability class. + * @return bool True when the class declares its own readiness check. + */ + private static function overrides_readiness( string $ability_class ): bool { + return Abstract_Core_Ability::class !== ( new ReflectionMethod( $ability_class, 'should_register' ) )->class; + } }