Commit d54a3a3e7ff for woocommerce
commit d54a3a3e7ff5262c4c992ba213b644a6e0c5fdf3
Author: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com>
Date: Thu Dec 3 08:54:59 2026 -0300
Let extensions write product term fields and make object_types work on every resource (#71568)
* Write extension fields in the product term abilities
The product term create and update abilities extend ActionableAbility.
They take extension fields, run the term validators before the save and
the term syncs after it, in one transaction. The terms query takes the
filters that extensions register for product_term.
A term is not a WC_Data object, so Core reads its ID and its type itself:
the type of a term is its taxonomy, and a field with object_types applies
to the terms of those taxonomies. An object without a type, such as a
review or a customer, gets every field of its resource.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Move the WC_Data save to a trait
Each ability now saves its own object. An ability for a WC_Data object
uses WCDataSaveTrait, and the term abilities keep their own save(). The
base save() throws when an ability has none, so it no longer refuses
objects that are not WC_Data.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Let each ability give the ID and the type of its objects
ActionableAbility asks the ability for the ID and the type of an object,
as it asks it to save. The domain traits answer once for their read and
write abilities: the type of a term is its taxonomy, and its ID is the
term ID. A read ability passes the type to add_fields_to_object().
ExtensibleAbilities no longer looks inside an object, so
get_object_type() is gone and field_applies_to() takes the type.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Read the ID and the type of an object from its resource
register_resource() takes an object_id_callback, which is required, and
an object_type_callback, which is optional. ActionableAbility and
ExtensibleAbilities read the ID and the type of every object through
them, so the abilities no longer hold that knowledge and
add_fields_to_object() keeps its three arguments.
A resource without a type callback has no type, and a field with
object_types is refused on it. The type of a term is its taxonomy, and
the type of a coupon is its discount type. The resources action also
fires with the feature off, because a write reads the ID from the
resource.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Require both callbacks on a resource and remove the fallbacks
Every resource now gives the ID and the type of its objects. A customer
returns its user role and a review its comment type, so no resource is
without a type. get_object_id() and get_object_type() return what the
callback returns, and throw for a resource that is not registered.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Keep the request exclude when a term filter returns an include list
WordPress ignores exclude next to include, so an include list from an extension filter brought back the terms the request excluded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Register Core's resources in the order tests with the feature off
A write reads the ID of its object from the resource also with the feature off, so a test that ran after another one could find no resource.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Return the save error when the resource of an ability is not registered
The rollback cleanup read object IDs from the resource, so an ability on a resource that is not registered threw a lookup exception instead of its own save error. The cleanup now skips those objects. The docblocks of get_deleted_objects() and get_trashed_objects() say that each object belongs to the resource of the ability.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Count each term once when a term meta filter matches several rows
WordPress counts every joined meta row in a term count query, so the total of product-terms-query could be higher than the number of terms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Refuse a write when the resource of an ability is not registered
Core reads the ID of each object from its resource, also with the feature off, so the check now runs at the start of every write instead of only for secondary objects with the feature on. The rollback cleanup no longer needs its own guard. Test classes that build write abilities register Core's resources through ExtensibleAbilitiesTestTrait.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Register the coupon resource, now that Core refuses writes on resources that are not registered
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Save WC_Data objects in the default save() of ActionableAbility
An ability for a WC_Data object no longer needs a trait to save it. The
default save() calls the new save_wc_data() helper, and an ability for
another kind of object overrides save().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the WC_Data save inside save() and drop the helper
ActionableAbility is a public class, so it keeps one save() method and no
extra protected helper. The order abilities call parent::save().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Clear the caches of rolled back objects with a callback of their resource, and cover coupons
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the ID of a new term before reading it back, so a rollback clears its cache
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Count distinct terms in SQL instead of loading every matching ID
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Isolate the extensible abilities in every order update test, and use the Core coupon resource in the coupon tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Name the rollback cache cleanup after what it does
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Register each Core resource on its own
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Move the rollback cache cleanup for coupons out of this change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/plugins/woocommerce/changelog/wooai-1746-term-extension-fields-and-object-types b/plugins/woocommerce/changelog/wooai-1746-term-extension-fields-and-object-types
new file mode 100644
index 00000000000..36846f0ebf6
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1746-term-extension-fields-and-object-types
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Let the product term abilities write extension fields, and read the ID and type of an object from its resource; the feature is experimental.
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index d4f9897e903..a6801b5b77c 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -32,6 +32,13 @@ defined( 'ABSPATH' ) || exit;
* input is ignored. An ability whose own input schema sets
* `additionalProperties` to false rejects it instead.
*
+ * Each ability saves its own object in save(). The ID and the type of an object
+ * come from the callbacks of its resource, so the resource must be registered
+ * with ExtensibleAbilities::register_resource(). The default save() saves a
+ * `WC_Data` object. An ability for a `WP_Term` sets the new values on the term
+ * in memory in change(), so the validators see them, and writes them in its own
+ * save().
+ *
* The object that load() returns is the primary object. An ability that saves
* more objects returns them from change(). These are the secondary objects. The field
* writes of every object run first, then the validators of each object's own
@@ -74,7 +81,7 @@ abstract class ActionableAbility extends Ability {
* @since 11.3.0
*
* @param array $input Ability input.
- * @return \WC_Data|\WP_Error
+ * @return object|\WP_Error
*/
abstract protected function load( array $input );
@@ -90,9 +97,9 @@ abstract class ActionableAbility extends Ability {
*
* @since 11.3.0
*
- * @param \WC_Data $subject Primary object to change.
- * @param array $input Ability input.
- * @return null|\WP_Error|array<int, array{0: \WC_Data, 1: array, 2?: string}> A WP_Error rejects the change, and nothing is saved. The field writes and the validators of the primary object still run, so the client gets their refusals in the same error. An array lists the secondary objects.
+ * @param object $subject Primary object to change.
+ * @param array $input Ability input.
+ * @return null|\WP_Error|array<int, array{0: object, 1: array, 2?: string}> A WP_Error rejects the change, and nothing is saved. The field writes and the validators of the primary object still run, so the client gets their refusals in the same error. An array lists the secondary objects.
*/
abstract protected function change( $subject, array $input );
@@ -102,24 +109,31 @@ abstract class ActionableAbility extends Ability {
*
* @since 11.3.0
*
- * @param \WC_Data $subject Saved object.
+ * @param object $subject Saved object.
* @return mixed|\WP_Error A WP_Error fails the call, but the change stays saved.
*/
abstract protected function prepare_response( $subject );
/**
- * Save the changed object. The default calls WC_Data::save(). An order's
- * save() catches a failed write, so the default reads that error from
+ * Save the changed object, and any secondary object. The default saves a
+ * `WC_Data` object with WC_Data::save(). An order's save() catches a failed
+ * write, so the default reads that error from
* WC_Abstract_Order::get_last_save_error(). When the save fails or leaves
* the object without an ID, it logs the error and returns a WP_Error with a
- * fixed message, so the exception text stays out of the response.
+ * fixed message, so the exception text stays out of the response. An ability
+ * for another kind of object, such as a `WP_Term`, overrides this method.
*
* @since 11.3.0
*
- * @param \WC_Data $subject Changed object.
+ * @param object $subject Changed object.
* @return null|\WP_Error Null when the object was saved, a WP_Error when it was not.
+ * @throws \BadMethodCallException When the object is not a `WC_Data` object and the ability does not override save().
*/
protected function save( $subject ) {
+ if ( ! $subject instanceof \WC_Data ) {
+ throw new \BadMethodCallException( esc_html( static::class . ' saves a ' . get_class( $subject ) . ', which is not a WC_Data object. Override save() to write it.' ) );
+ }
+
try {
$subject->save();
$error = $subject instanceof \WC_Abstract_Order ? $subject->get_last_save_error() : null;
@@ -166,11 +180,12 @@ abstract class ActionableAbility extends Ability {
/**
* The objects that save() deleted for good, for the syncs. An ability that
- * deletes objects collects them in save() and returns them here.
+ * deletes objects collects them in save() and returns them here. Each object
+ * belongs to the resource of the ability, which gives its ID.
*
* @since 11.4.0
*
- * @return \WC_Data[]
+ * @return object[]
*/
protected function get_deleted_objects(): array {
return array();
@@ -178,11 +193,12 @@ abstract class ActionableAbility extends Ability {
/**
* The objects that save() moved to the trash, for the syncs. A trashed
- * object can be restored, so a sync keeps what a restore needs.
+ * object can be restored, so a sync keeps what a restore needs. Each object
+ * belongs to the resource of the ability, which gives its ID.
*
* @since 11.4.0
*
- * @return \WC_Data[]
+ * @return object[]
*/
protected function get_trashed_objects(): array {
return array();
@@ -196,7 +212,7 @@ abstract class ActionableAbility extends Ability {
*
* @since 11.4.0
*
- * @return \WC_Data[]
+ * @return object[]
*/
protected function get_objects_to_delete(): array {
return array();
@@ -212,6 +228,10 @@ abstract class ActionableAbility extends Ability {
* @throws \Throwable When save() throws, after the rollback.
*/
public function execute_change( $input = null ) {
+ if ( ! ExtensibleAbilities::is_resource_registered( $this->get_resource() ) ) {
+ return $this->unknown_resource_error( $this->get_resource(), 'get_resource' );
+ }
+
$input = is_array( $input ) ? $input : array();
$subject = $this->load( $input );
if ( is_wp_error( $subject ) ) {
@@ -251,29 +271,8 @@ abstract class ActionableAbility extends Ability {
$objects = array( array( $subject, $updates, $this->get_resource() ) );
foreach ( (array) $changed as $secondary ) {
$resource_name = $secondary[2] ?? $this->get_resource();
- if ( $enabled && ! ExtensibleAbilities::is_resource_registered( $resource_name ) ) {
- wc_doing_it_wrong(
- get_class( $this ) . '::change',
- sprintf(
- 'The "%s" resource of a secondary object is not registered, so the call is refused. Call ExtensibleAbilities::register_resource() first.',
- $resource_name
- ),
- '11.4.0'
- );
- return new \WP_Error(
- 'woocommerce_ability_resource_unknown',
- sprintf(
- /* translators: 1: resource name, 2: ability name. */
- __( 'The "%1$s" resource is not registered, so the "%2$s" ability cannot save the change.', 'woocommerce' ),
- $resource_name,
- $this->get_name()
- ),
- array(
- 'status' => 500,
- 'resource' => $resource_name,
- 'ability' => $this->get_name(),
- )
- );
+ if ( ! ExtensibleAbilities::is_resource_registered( $resource_name ) ) {
+ return $this->unknown_resource_error( $resource_name, 'change' );
}
$fields = $writes ? $this->prepare_fields( $secondary[1], $resource_name ) : array();
if ( is_wp_error( $fields ) ) {
@@ -322,41 +321,75 @@ abstract class ActionableAbility extends Ability {
}
);
} catch ( \Throwable $e ) {
- self::forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
+ $this->forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
throw $e;
}
if ( is_wp_error( $saved ) ) {
- self::forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
+ $this->forget_rolled_back_objects( $objects, array_merge( $this->get_deleted_objects(), $this->get_trashed_objects() ) );
return $saved;
}
$response = $this->prepare_response( $subject );
if ( is_wp_error( $response ) ) {
- return ExtensibleAbilities::saved_write_error( $response, $this->get_resource(), $subject->get_id() );
+ return ExtensibleAbilities::saved_write_error( $response, $this->get_resource(), ExtensibleAbilities::get_object_id( $subject, $this->get_resource() ) );
}
return $response;
}
+ /**
+ * Refuse a call whose primary or secondary object has a resource that is not registered,
+ * before anything is saved. Core reads the ID of each object from its resource, also with the feature off.
+ *
+ * @param string $resource_name Resource that is not registered.
+ * @param string $method Method of the ability that names the resource.
+ * @return \WP_Error
+ */
+ private function unknown_resource_error( string $resource_name, string $method ): \WP_Error {
+ wc_doing_it_wrong(
+ get_class( $this ) . '::' . $method,
+ sprintf(
+ 'The "%s" resource is not registered, so the call is refused. Call ExtensibleAbilities::register_resource() first.',
+ $resource_name
+ ),
+ '11.4.0'
+ );
+ return new \WP_Error(
+ 'woocommerce_ability_resource_unknown',
+ sprintf(
+ /* translators: 1: resource name, 2: ability name. */
+ __( 'The "%1$s" resource is not registered, so the "%2$s" ability cannot save the change.', 'woocommerce' ),
+ $resource_name,
+ $this->get_name()
+ ),
+ array(
+ 'status' => 500,
+ 'resource' => $resource_name,
+ 'ability' => $this->get_name(),
+ )
+ );
+ }
+
/**
* Run the syncs of each resource that the call saved or deleted, once,
* after the last save and before the commit. A sync gets the saved objects
* of its own resource. A deleted or trashed object is not in the saved
* list, even when it was the primary object.
*
- * @param array<int, array{0: \WC_Data, 1: array, 2: string}> $objects The primary object and the secondary objects, with their resources.
+ * @param array<int, array{0: object, 1: array, 2: string}> $objects The primary object and the secondary objects, with their resources.
* @param array<string, \SplObjectStorage<object, array<string, mixed>>> $sent The sent field values of each namespace, from apply_fields().
* @return \WP_Error|null A WP_Error when a sync refused, and then the call rolls back.
*/
private function sync( array $objects, array $sent ): ?\WP_Error {
$deleted = $this->get_deleted_objects();
$trashed = $this->get_trashed_objects();
- $gone = array_map( static fn( $item ) => get_class( $item ) . ':' . $item->get_id(), array_merge( $deleted, $trashed ) );
+ $gone = array_map( fn( $item ) => get_class( $item ) . ':' . ExtensibleAbilities::get_object_id( $item, $this->get_resource() ), array_merge( $deleted, $trashed ) );
$saved = array();
$own = array();
foreach ( $objects as list( $object, , $resource_name ) ) {
$own[ $resource_name ] ??= array();
- if ( $object->get_id() > 0 && ! in_array( get_class( $object ) . ':' . $object->get_id(), $gone, true ) ) {
+ $id = ExtensibleAbilities::get_object_id( $object, $resource_name );
+ if ( $id > 0 && ! in_array( get_class( $object ) . ':' . $id, $gone, true ) ) {
$saved[] = $object;
$own[ $resource_name ][] = $object;
}
@@ -385,15 +418,16 @@ abstract class ActionableAbility extends Ability {
* saves filled the caches with rows the rollback removed, so a read in the
* same request would still see them. The `WC_Data` meta cache, the product type cache, the
* product instance cache and the price lookup cache are separate from the post cache.
+ * A term has its own object cache and meta cache.
*
- * @param array<int, array{0: \WC_Data, 1: array, 2: string}> $objects The primary object and the secondary objects.
- * @param \WC_Data[] $deleted The objects the call deleted.
+ * @param array<int, array{0: object, 1: array, 2: string}> $objects The primary object and the secondary objects.
+ * @param object[] $deleted The objects the call deleted.
*/
- private static function forget_rolled_back_objects( array $objects, array $deleted = array() ): void {
+ private function forget_rolled_back_objects( array $objects, array $deleted = array() ): void {
$product_cache = wc_get_container()->get( ProductCache::class );
- foreach ( array_merge( $objects, array_map( static fn( $item ) => array( $item ), $deleted ) ) as list( $object ) ) {
- $id = $object->get_id();
- if ( $id > 0 ) {
+ foreach ( array_merge( $objects, array_map( fn( $item ) => array( $item, array(), $this->get_resource() ), $deleted ) ) as list( $object, , $resource_name ) ) {
+ $id = ExtensibleAbilities::get_object_id( $object, $resource_name );
+ if ( $id > 0 && $object instanceof \WC_Data ) {
$object->delete_meta_cache();
}
if ( $id > 0 && $object instanceof \WC_Product ) {
@@ -413,6 +447,9 @@ abstract class ActionableAbility extends Ability {
clean_post_cache( $id );
} elseif ( $id > 0 && $object instanceof \WC_Customer ) {
clean_user_cache( $id );
+ } elseif ( $id > 0 && $object instanceof \WP_Term ) {
+ clean_term_cache( $id, $object->taxonomy );
+ wp_cache_delete( $id, 'term_meta' );
}
}
}
@@ -590,7 +627,7 @@ abstract class ActionableAbility extends Ability {
* rejection goes into the given errors, as add_refusal() describes. Each
* value that was not rejected goes into the sent values of its namespace.
*
- * @param \WC_Data $subject Object to change.
+ * @param object $subject Object to change.
* @param array $updates Pairs of field arguments and value from prepare_fields().
* @param array<string, \SplObjectStorage<object, array<string, mixed>>> $sent Collects the sent values, as get_sent_fields() describes.
* @param \WP_Error $refused Collects the refusals, including a field that does not apply to the object.
@@ -604,7 +641,7 @@ abstract class ActionableAbility extends Ability {
/* translators: 1: extension field, 2: object type, 3: comma-separated list of object types. */
__( 'The %1$s field does not apply to the %2$s type. It applies to %3$s.', 'woocommerce' ),
$param,
- ExtensibleAbilities::get_object_type( $subject ),
+ ExtensibleAbilities::get_object_type( $subject, $args['resource'] ),
implode( ', ', $args['object_types'] )
),
array( 'status' => 400 )
@@ -652,7 +689,7 @@ abstract class ActionableAbility extends Ability {
* Run every validator of a resource on the changed object, also after a
* field or another validator refuses.
*
- * @param \WC_Data $subject Changed object.
+ * @param object $subject Changed object.
* @param string $resource_name Resource of the object.
* @param array $context The name of the ability, the primary object of the call, whether the call deletes or trashes the object, the objects the call saves, and the objects it deletes or trashes.
* @param array<string, \SplObjectStorage<object, array<string, mixed>>> $sent The sent field values of each namespace, from apply_fields().
@@ -766,9 +803,11 @@ abstract class ActionableAbility extends Ability {
/**
* The error for a save that failed.
*
+ * @since 11.5.0
+ *
* @return \WP_Error
*/
- private static function save_failed(): \WP_Error {
+ protected static function save_failed(): \WP_Error {
return new \WP_Error(
'woocommerce_ability_save_failed',
__( 'The change could not be saved.', 'woocommerce' ),
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index f828eb62444..a6fdfcb43e7 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -43,9 +43,9 @@ class ExtensibleAbilities {
private static array $fields = array();
/**
- * Registered resources, keyed by resource name.
+ * Registered resources, keyed by resource name. The value holds the arguments from `register_resource()`.
*
- * @var array<string, bool>
+ * @var array<string, array<string, mixed>>
*/
private static array $resources = array();
@@ -109,16 +109,28 @@ class ExtensibleAbilities {
* Register a resource that abilities format, so extensions can register fields on it.
*
* Call it inside the `woocommerce_extensible_abilities_resources_init` action. A call after that action is refused.
- * Core registers `product`, `order` and `order_item` there. An
- * extension registers a resource that its own abilities format, and then calls `add_fields_to_object()`
- * and `add_fields_schema()` from those abilities, exactly as Core's abilities do.
+ * Core registers `product`, `order`, `order_item`, `order_refund`, `product_term`, `product_review`, `customer`
+ * and `coupon` there. An extension registers a resource that its own abilities format, and then calls
+ * `add_fields_to_object()` and `add_fields_schema()` from those abilities, exactly as Core's abilities do.
* Registering the same resource again does nothing.
*
* @since 11.3.0
*
* @param string $resource_name Slug of the resource, such as `ticket`.
+ * @param array $args {
+ * Arguments of the resource. Both callbacks are required.
+ *
+ * @type callable $object_id_callback Receives an object of the resource and returns its ID as an integer,
+ * or zero when the object is not saved yet. Core's `product` returns
+ * `get_id()` and its `product_term` returns the term ID.
+ * @type callable $object_type_callback Receives an object of the resource and returns its type as a string,
+ * which the `object_types` of a field are compared with. Core's `product`
+ * returns `get_type()`, its `product_term` the taxonomy, its `coupon` the
+ * discount type, its `customer` the user role and its `product_review`
+ * the comment type.
+ * }
*/
- public static function register_resource( string $resource_name ): void {
+ public static function register_resource( string $resource_name, array $args = array() ): void {
if ( did_action( 'woocommerce_extensible_abilities_resources_init' ) && ! doing_action( 'woocommerce_extensible_abilities_resources_init' ) ) {
wc_doing_it_wrong( __METHOD__, 'Register a resource inside the woocommerce_extensible_abilities_resources_init action, before the fields are registered.', '11.3.0' );
return;
@@ -127,8 +139,14 @@ class ExtensibleAbilities {
wc_doing_it_wrong( __METHOD__, 'The resource name must be a slug of lowercase letters, numbers, dashes and underscores, not only numbers.', '11.3.0' );
return;
}
+ foreach ( array( 'object_id_callback', 'object_type_callback' ) as $callback ) {
+ if ( ! isset( $args[ $callback ] ) || ! is_callable( $args[ $callback ] ) ) {
+ wc_doing_it_wrong( __METHOD__, sprintf( 'The "%1$s" resource needs a callable "%2$s" argument.', $resource_name, $callback ), '11.5.0' );
+ return;
+ }
+ }
- self::$resources[ $resource_name ] = true;
+ self::$resources[ $resource_name ] = self::$resources[ $resource_name ] ?? $args;
}
/**
@@ -139,10 +157,10 @@ class ExtensibleAbilities {
* A field declares `get_callback` and `output_schema` to be readable, and `input_schema` to be writable.
* A `set_callback` is optional on a writable field, and it is refused without `input_schema`.
*
- * There are two kinds of writable field. A field kept on the object, such as a meta value, has a
+ * There are two kinds of writable field. A field kept on a `WC_Data` object, such as a meta value, has a
* `set_callback` that stages the value, and Core saves it with the object. A field kept elsewhere, such
- * as a row in a table of the extension, has no `set_callback`: a sync that register_sync() adds writes
- * the value from `$context['fields']`.
+ * as a row in a table of the extension or the meta of a term, has no `set_callback`: a sync that
+ * register_sync() adds writes the value from `$context['fields']`.
*
* @since 11.3.0
*
@@ -163,14 +181,13 @@ class ExtensibleAbilities {
* which are the keywords with a nested schema that WordPress supports (see
* `rest_get_allowed_schema_keywords()`), and under `allOf`, which
* WooCommerce also reads, because some clients refuse it.
- * @type string[] $object_types Optional. The object types the field applies to, as `get_type()` of the
- * object returns them, such as `simple` and `subscription` for a product or
- * `line_item`, `shipping`, `fee` and `coupon` for an order item. The object
- * must have a `get_type()` method.
- * The abilities leave the field out of the other objects, and an ability
- * that writes the resource refuses a write to them. Omit it for every type:
- * an `order_item` field without it is then read on product, shipping, fee
- * and coupon lines, so its `get_callback` must accept each of them.
+ * @type string[] $object_types Optional. The object types the field applies to, as the `object_type_callback` of
+ * the resource returns them, such as `simple` and `subscription` for a product,
+ * `line_item`, `shipping`, `fee` and `coupon` for an order item or `product_brand`
+ * for a term. The abilities leave the field out of the other objects, and an ability
+ * that writes the resource refuses a write to them. Omit it for every type: an
+ * `order_item` field without it is then read on product, shipping, fee and coupon
+ * lines, so its `get_callback` must accept each of them.
* @type callable $get_callback Optional. Receives the object and returns the value. A field without it
* is not in the output. Required with `output_schema`. Return null when the
* object has no value, and the field is left out with no error. Any other
@@ -371,8 +388,9 @@ class ExtensibleAbilities {
* Filter arguments.
*
* @type string $resource Resource whose list ability applies the filters. Core's `products-query`,
- * `orders-query` and `customers-query` apply the filters of `product`, `order`
- * and `customer`. A `customer` filter returns only `include_ids`, which are
+ * `orders-query`, `customers-query` and `product-terms-query` apply the filters
+ * of `product`, `order`, `customer` and `product_term`. A `product_term`
+ * `meta_query` reads term meta. A `customer` filter returns only `include_ids`, which are
* user IDs, so it matches registered customers only. The list ability
* of another resource must call `get_query_args()` and `add_query_filters_schema()` itself.
* @type string $namespace Slug of the extension that owns the filter, such as `subscriptions`.
@@ -688,7 +706,7 @@ class ExtensibleAbilities {
*
* @type string $resource Resource that an ActionableAbility saves, such as `product`.
* @type string $namespace Slug of the extension that owns the sync, such as `subscriptions`.
- * @type callable $callback Receives `\WC_Data[] $saved` and `array $context`.
+ * @type callable $callback Receives `object[] $saved` and `array $context`.
* `$saved` is every saved object of the sync's own resource. The context
* describes the whole call.
* `$context['ability']` is the name of the ability, such as
@@ -974,23 +992,53 @@ class ExtensibleAbilities {
* @since 11.4.0
*
* @param array<string, mixed> $args Field arguments from `register_field()`.
- * @param mixed $subject The object. It must have a `get_type()` method.
+ * @param mixed $subject The object.
* @return bool
*/
public static function field_applies_to( array $args, $subject ): bool {
- return empty( $args['object_types'] ) || in_array( $subject->get_type(), $args['object_types'], true );
+ return empty( $args['object_types'] ) || in_array( self::get_object_type( $subject, $args['resource'] ), $args['object_types'], true );
}
/**
- * The type of an object, from its `get_type()` method.
+ * The type of an object, from the `object_type_callback` of its resource.
*
* @since 11.4.0
*
- * @param mixed $subject The object. It must have a `get_type()` method.
+ * @param mixed $subject The object.
+ * @param string $resource_name Resource of the object.
* @return string
+ * @throws \LogicException When the resource is not registered.
*/
- public static function get_object_type( $subject ): string {
- return $subject->get_type();
+ public static function get_object_type( $subject, string $resource_name ): string {
+ return call_user_func( self::get_registered_resource( $resource_name )['object_type_callback'], $subject );
+ }
+
+ /**
+ * The ID of an object, from the `object_id_callback` of its resource.
+ *
+ * @since 11.5.0
+ *
+ * @param mixed $subject The object.
+ * @param string $resource_name Resource of the object.
+ * @return int The ID, or zero when the object is not saved yet.
+ * @throws \LogicException When the resource is not registered.
+ */
+ public static function get_object_id( $subject, string $resource_name ): int {
+ return call_user_func( self::get_registered_resource( $resource_name )['object_id_callback'], $subject );
+ }
+
+ /**
+ * The arguments of a registered resource.
+ *
+ * @param string $resource_name Resource.
+ * @return array<string, mixed>
+ * @throws \LogicException When the resource is not registered.
+ */
+ private static function get_registered_resource( string $resource_name ): array {
+ if ( ! isset( self::$resources[ $resource_name ] ) ) {
+ throw new \LogicException( esc_html( sprintf( 'The "%s" resource is not registered. Call ExtensibleAbilities::register_resource() inside the woocommerce_extensible_abilities_resources_init action.', $resource_name ) ) );
+ }
+ return self::$resources[ $resource_name ];
}
/**
diff --git a/plugins/woocommerce/src/Internal/Abilities/AGENTS.md b/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
index 2e259776ce1..454c8ea7607 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
+++ b/plugins/woocommerce/src/Internal/Abilities/AGENTS.md
@@ -36,7 +36,7 @@ Do not use `destructive` for this. An ability with `destructive: false`, such as
A test that needs the `extensible_abilities` feature on uses `Automattic\WooCommerce\Tests\Internal\Abilities\ExtensibleAbilitiesTestTrait`. Do not turn the feature on with `update_option()` alone, fire the init actions by hand, or reach into the registries of `ExtensibleAbilities` with reflection.
- Call `enable_extensible_abilities()` to turn the feature on with Core's resources registered. Pass a callback to register the fields, validators, syncs or filters of the test.
-- Call `isolate_extensible_abilities()` when the test needs empty registries while the feature is off.
+- Call `isolate_extensible_abilities()` when the feature is off. It empties the registries and registers Core's resources, because a write ability refuses a call when its resource is not registered, also with the feature off.
- Do not restore anything by hand. The trait restores the registries after each test.
Turning only the option on is not enough. When an earlier test built the abilities registry while the feature was off, Core's resources are not registered, and an ability that saves a secondary object refuses the call.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 917c2512474..82903ffdd52 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -178,9 +178,64 @@ class AbilitiesLoader {
* @since 11.3.0
*/
public static function register_core_resources(): void {
- foreach ( array( 'product', 'order', 'order_item', 'order_refund', 'product_term', 'product_review', 'customer' ) as $resource_name ) {
- ExtensibleAbilities::register_resource( $resource_name );
- }
+ $data_id = static fn( \WC_Data $data ): int => $data->get_id();
+ $data_type = static fn( $data ): string => $data->get_type();
+ ExtensibleAbilities::register_resource(
+ 'product',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => $data_type,
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'order',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => $data_type,
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'order_item',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => $data_type,
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'order_refund',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => $data_type,
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'coupon',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => static fn( \WC_Coupon $coupon ): string => $coupon->get_discount_type(),
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'customer',
+ array(
+ 'object_id_callback' => $data_id,
+ 'object_type_callback' => static fn( \WC_Customer $customer ): string => $customer->get_role(),
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'product_review',
+ array(
+ 'object_id_callback' => static fn( \WP_Comment $comment ): int => (int) $comment->comment_ID,
+ 'object_type_callback' => static fn( \WP_Comment $comment ): string => $comment->comment_type,
+ )
+ );
+ ExtensibleAbilities::register_resource(
+ 'product_term',
+ array(
+ 'object_id_callback' => static fn( \WP_Term $term ): int => $term->term_id,
+ 'object_type_callback' => static fn( \WP_Term $term ): string => $term->taxonomy,
+ )
+ );
}
/**
@@ -215,20 +270,23 @@ class AbilitiesLoader {
* @since 11.3.0
*/
public static function init_extensions(): void {
+ if ( ! did_action( 'woocommerce_extensible_abilities_resources_init' ) ) {
+ /**
+ * Fires when extensions can register their resources with ExtensibleAbilities.
+ *
+ * Fires one time, before `woocommerce_extensible_abilities_init`. It also fires when the
+ * experimental `extensible_abilities` feature is off, because an ability that writes a
+ * resource reads the ID of its objects from the resource.
+ *
+ * @since 11.3.0
+ */
+ do_action( 'woocommerce_extensible_abilities_resources_init' );
+ }
+
if ( did_action( 'woocommerce_extensible_abilities_init' ) || ! ExtensibleAbilities::is_enabled() ) {
return;
}
- /**
- * Fires when extensions can register their resources with ExtensibleAbilities.
- *
- * Fires one time, before `woocommerce_extensible_abilities_init`, only when the
- * experimental `extensible_abilities` feature is on.
- *
- * @since 11.3.0
- */
- do_action( 'woocommerce_extensible_abilities_resources_init' );
-
/**
* Fires when extensions can register their fields with ExtensibleAbilities.
*
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermCreate.php
index 6fec586ea61..d938947d412 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermCreate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermCreate.php
@@ -7,28 +7,24 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Internal\Abilities\Domain;
-use Automattic\WooCommerce\Abilities\AbilityDefinition;
-use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductTermAbilityTrait;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductTermWriteTrait;
defined( 'ABSPATH' ) || exit;
/**
* Creates a product category, tag, brand or global attribute term.
*/
-class ProductTermCreate extends AbstractDomainAbility implements AbilityDefinition {
+class ProductTermCreate extends ActionableAbility {
use ProductTermAbilityTrait;
+ use ProductTermWriteTrait;
+ use DomainAbilityHelpers;
- /**
- * Get the ability name.
- *
- * @since 11.4.0
- * @return string
- */
- public static function get_name(): string {
- return 'woocommerce/product-term-create';
- }
+ /** Ability name. */
+ public const ABILITY_NAME = 'woocommerce/product-term-create';
/**
* Get the ability registration arguments.
@@ -41,9 +37,8 @@ class ProductTermCreate extends AbstractDomainAbility implements AbilityDefiniti
'label' => __( 'Create product term', 'woocommerce' ),
'description' => __( 'Create a product category, tag, brand or a term of a global attribute, such as pa_color. Product writes then assign it by ID.', 'woocommerce' ),
'category' => 'woocommerce',
- 'input_schema' => self::get_input_schema(),
+ 'input_schema' => self::build_input_schema(),
'output_schema' => self::get_entity_output_schema( 'term', self::get_written_term_output_schema() ),
- 'execute_callback' => array( __CLASS__, 'execute' ),
'permission_callback' => array( __CLASS__, 'can_create_term' ),
'meta' => array(
'show_in_rest' => true,
@@ -72,49 +67,51 @@ class ProductTermCreate extends AbstractDomainAbility implements AbilityDefiniti
}
/**
- * Create a product term.
+ * Build the new term in memory.
*
- * @since 11.4.0
* @param array $input Ability input.
- * @return array|\WP_Error
+ * @return \WP_Term|\WP_Error
*/
- public static function execute( array $input ) {
- $taxonomy = $input['taxonomy'];
- if ( ! self::is_writable_product_taxonomy( $taxonomy ) ) {
- return self::get_unknown_taxonomy_error( $taxonomy );
+ protected function load( array $input ) {
+ $this->term_args = array();
+ if ( ! self::is_writable_product_taxonomy( $input['taxonomy'] ) ) {
+ return self::get_unknown_taxonomy_error( $input['taxonomy'] );
}
+ return new \WP_Term(
+ (object) array(
+ 'term_id' => 0,
+ 'taxonomy' => $input['taxonomy'],
+ )
+ );
+ }
+
+ /**
+ * Set the term fields in memory.
+ *
+ * @param \WP_Term $subject New term.
+ * @param array $input Ability input.
+ * @return null|\WP_Error
+ */
+ protected function change( $subject, array $input ) {
$name = sanitize_text_field( $input['name'] );
$slug = isset( $input['slug'] ) ? sanitize_title( $input['slug'] ) : null;
$parent = $input['parent'] ?? 0;
- $error = self::check_term_write( $taxonomy, $name, $slug, $parent );
+ $error = self::check_term_write( $subject->taxonomy, $name, $slug, $parent );
if ( $error ) {
return $error;
}
$args = array(
+ 'name' => $name,
'parent' => $parent,
'description' => wp_kses_post( $input['description'] ?? '' ),
);
if ( null !== $slug ) {
$args['slug'] = $slug;
}
- $ids = wp_insert_term( wp_slash( $name ), $taxonomy, wp_slash( $args ) );
- if ( is_wp_error( $ids ) ) {
- return new \WP_Error( 'woocommerce_ability_product_term_create_failed', $ids->get_error_message(), array( 'status' => 500 ) );
- }
-
- $term = get_term( $ids['term_id'], $taxonomy );
- if ( ! $term instanceof \WP_Term ) {
- return new \WP_Error( 'woocommerce_ability_product_term_create_failed', __( 'The term was created but could not be read back.', 'woocommerce' ), array( 'status' => 500 ) );
- }
-
- $output = self::format_term( $term );
- if ( is_wp_error( $output ) ) {
- return ExtensibleAbilities::saved_write_error( $output, 'product_term', $term->term_id );
- }
-
- return array( 'term' => $output );
+ $this->stage_term_args( $subject, $args );
+ return null;
}
/**
@@ -122,7 +119,7 @@ class ProductTermCreate extends AbstractDomainAbility implements AbilityDefiniti
*
* @return array
*/
- private static function get_input_schema(): array {
+ private static function build_input_schema(): array {
$properties = self::get_term_write_properties();
$properties['slug']['description'] = __( 'Defaults to one made from the name.', 'woocommerce' );
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermUpdate.php
index 1ab9b6c96ab..9204f693cad 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermUpdate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermUpdate.php
@@ -7,28 +7,24 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Internal\Abilities\Domain;
-use Automattic\WooCommerce\Abilities\AbilityDefinition;
-use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductTermAbilityTrait;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductTermWriteTrait;
defined( 'ABSPATH' ) || exit;
/**
* Renames, re-slugs, moves or redescribes a product category, tag, brand or global attribute term.
*/
-class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefinition {
+class ProductTermUpdate extends ActionableAbility {
use ProductTermAbilityTrait;
+ use ProductTermWriteTrait;
+ use DomainAbilityHelpers;
- /**
- * Get the ability name.
- *
- * @since 11.4.0
- * @return string
- */
- public static function get_name(): string {
- return 'woocommerce/product-term-update';
- }
+ /** Ability name. */
+ public const ABILITY_NAME = 'woocommerce/product-term-update';
/**
* Get the ability registration arguments.
@@ -41,9 +37,8 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
'label' => __( 'Update product term', 'woocommerce' ),
'description' => __( 'Change the name, slug, parent or description of a product category, tag, brand or global attribute term. Fields left out keep their value.', 'woocommerce' ),
'category' => 'woocommerce',
- 'input_schema' => self::get_input_schema(),
+ 'input_schema' => self::build_input_schema(),
'output_schema' => self::get_entity_output_schema( 'term', self::get_written_term_output_schema() ),
- 'execute_callback' => array( __CLASS__, 'execute' ),
'permission_callback' => array( __CLASS__, 'can_update_term' ),
'meta' => array(
'show_in_rest' => true,
@@ -72,14 +67,14 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
}
/**
- * Update a product term.
+ * Load the term to change.
*
- * @since 11.4.0
* @param array $input Ability input.
- * @return array|\WP_Error
+ * @return \WP_Term|\WP_Error
*/
- public static function execute( array $input ) {
- $taxonomy = $input['taxonomy'];
+ protected function load( array $input ) {
+ $this->term_args = array();
+ $taxonomy = $input['taxonomy'];
if ( ! self::is_writable_product_taxonomy( $taxonomy ) ) {
return self::get_unknown_taxonomy_error( $taxonomy );
}
@@ -93,8 +88,18 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
array( 'status' => 404 )
);
}
+ return $term;
+ }
- if ( ! array_intersect_key( $input, self::get_term_write_properties() ) ) {
+ /**
+ * Set the sent term fields in memory.
+ *
+ * @param \WP_Term $subject Term.
+ * @param array $input Ability input.
+ * @return null|\WP_Error
+ */
+ protected function change( $subject, array $input ) {
+ if ( ! array_intersect_key( $input, self::get_term_write_properties() + array( 'extensions' => true ) ) ) {
return new \WP_Error(
'woocommerce_ability_product_term_no_fields',
__( 'No change was sent. Send at least one term field to change, in addition to the id.', 'woocommerce' ),
@@ -102,12 +107,12 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
);
}
- $name = isset( $input['name'] ) ? sanitize_text_field( $input['name'] ) : wp_specialchars_decode( $term->name, ENT_QUOTES );
+ $name = isset( $input['name'] ) ? sanitize_text_field( $input['name'] ) : wp_specialchars_decode( $subject->name, ENT_QUOTES );
$slug = isset( $input['slug'] ) ? sanitize_title( $input['slug'] ) : null;
- $parent = $input['parent'] ?? $term->parent;
+ $parent = $input['parent'] ?? $subject->parent;
// Only a new name or parent can collide with a sibling's name.
$checked_name = isset( $input['name'] ) || isset( $input['parent'] ) ? $name : null;
- $error = self::check_term_write( $taxonomy, $checked_name, $slug, $parent, $term->term_id );
+ $error = self::check_term_write( $subject->taxonomy, $checked_name, $slug, $parent, $subject->term_id );
if ( $error ) {
return $error;
}
@@ -125,22 +130,8 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
if ( isset( $input['description'] ) ) {
$args['description'] = wp_kses_post( $input['description'] );
}
- $result = wp_update_term( $term->term_id, $taxonomy, wp_slash( $args ) );
- if ( is_wp_error( $result ) ) {
- return new \WP_Error( 'woocommerce_ability_product_term_update_failed', $result->get_error_message(), array( 'status' => 500 ) );
- }
-
- $term = get_term( $term->term_id, $taxonomy );
- if ( ! $term instanceof \WP_Term ) {
- return new \WP_Error( 'woocommerce_ability_product_term_update_failed', __( 'The term was updated but could not be read back.', 'woocommerce' ), array( 'status' => 500 ) );
- }
-
- $output = self::format_term( $term );
- if ( is_wp_error( $output ) ) {
- return ExtensibleAbilities::saved_write_error( $output, 'product_term', $term->term_id );
- }
-
- return array( 'term' => $output );
+ $this->stage_term_args( $subject, $args );
+ return null;
}
/**
@@ -148,7 +139,7 @@ class ProductTermUpdate extends AbstractDomainAbility implements AbilityDefiniti
*
* @return array
*/
- private static function get_input_schema(): array {
+ private static function build_input_schema(): array {
return array(
'type' => 'object',
'properties' => array_merge(
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermsQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermsQuery.php
index 10c297c19ce..a3465f3a59d 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermsQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductTermsQuery.php
@@ -116,6 +116,27 @@ class ProductTermsQuery extends AbstractDomainAbility implements AbilityDefiniti
$args['object_ids'] = array( $input['product'] );
}
+ $extension_args = ExtensibleAbilities::get_query_args( 'product_term', $input );
+ if ( is_wp_error( $extension_args ) ) {
+ return $extension_args;
+ }
+ if ( isset( $extension_args['meta_query'] ) ) {
+ $args['meta_query'] = $extension_args['meta_query']; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- The filters of extensions read term meta.
+ }
+ $excluded = $extension_args['post__not_in'] ?? array();
+ $include = $args['include'] ?? $extension_args['post__in'] ?? null;
+ if ( isset( $args['include'], $extension_args['post__in'] ) ) {
+ $include = array_intersect( $include, $extension_args['post__in'] );
+ }
+ if ( null !== $include ) {
+ // WordPress ignores exclude next to include, and an empty include does not filter.
+ $include = array_values( array_diff( $include, $excluded, isset( $args['include'] ) ? array() : ( $args['exclude'] ?? array() ) ) );
+ $args['include'] = empty( $include ) ? array( 0 ) : $include;
+ }
+ if ( ! empty( $excluded ) ) {
+ $args['exclude'] = array_merge( $args['exclude'] ?? array(), $excluded );
+ }
+
add_filter( 'terms_clauses', array( __CLASS__, 'add_id_tiebreak' ), PHP_INT_MAX );
$terms = get_terms( $args );
remove_filter( 'terms_clauses', array( __CLASS__, 'add_id_tiebreak' ), PHP_INT_MAX );
@@ -126,7 +147,9 @@ class ProductTermsQuery extends AbstractDomainAbility implements AbilityDefiniti
unset( $count_args['number'], $count_args['offset'] );
// WordPress count queries skip hierarchy-based hide_empty filtering.
$count_args['fields'] = $args['hide_empty'] && is_taxonomy_hierarchical( $args['taxonomy'] ) ? 'ids' : 'count';
- $total = get_terms( $count_args );
+ add_filter( 'terms_clauses', array( __CLASS__, 'count_distinct_terms' ), PHP_INT_MAX );
+ $total = get_terms( $count_args );
+ remove_filter( 'terms_clauses', array( __CLASS__, 'count_distinct_terms' ), PHP_INT_MAX );
if ( is_wp_error( $total ) ) {
return $total;
}
@@ -178,13 +201,32 @@ class ProductTermsQuery extends AbstractDomainAbility implements AbilityDefiniti
return $clauses;
}
+ /**
+ * Count each term once. A meta query joins term meta, so `COUNT(*)` counts
+ * a term once per matching meta row.
+ *
+ * @internal
+ *
+ * @since 11.5.0
+ *
+ * @param mixed $clauses Term query clauses.
+ * @return mixed
+ */
+ public static function count_distinct_terms( $clauses ) {
+ if ( is_array( $clauses ) && 'COUNT(*)' === ( $clauses['fields'] ?? '' ) ) {
+ $clauses['fields'] = 'COUNT(DISTINCT t.term_id)';
+ }
+
+ return $clauses;
+ }
+
/**
* Get the input schema.
*
* @return array
*/
private static function get_input_schema(): array {
- return array(
+ $schema = array(
'type' => 'object',
'properties' => array(
'taxonomy' => self::get_taxonomy_input_schema( __( 'Product taxonomy to query: product_cat, product_tag, product_brand, or the slug of a global attribute from product-attributes-query.', 'woocommerce' ) ),
@@ -254,5 +296,6 @@ class ProductTermsQuery extends AbstractDomainAbility implements AbilityDefiniti
'required' => array( 'taxonomy' ),
'additionalProperties' => false,
);
+ return ExtensibleAbilities::add_query_filters_schema( $schema, 'product_term' );
}
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php
new file mode 100644
index 00000000000..50e9aff281e
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductTermWriteTrait.php
@@ -0,0 +1,90 @@
+<?php
+/**
+ * Product term write helpers.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Saves the `WP_Term` of the product term create and update abilities, which extend ActionableAbility.
+ */
+trait ProductTermWriteTrait {
+
+ /**
+ * The term fields that change() checked and save() writes.
+ *
+ * @var array{name?: string, slug?: string, parent?: int, description?: string}
+ */
+ private array $term_args = array();
+
+ /**
+ * Resource being changed.
+ *
+ * @return string
+ */
+ public function get_resource(): string {
+ return 'product_term';
+ }
+
+ /**
+ * Keep the checked term fields for save(), and set them on the term in memory, so validators see the change.
+ *
+ * @param \WP_Term $term Term.
+ * @param array{name?: string, slug?: string, parent?: int, description?: string} $args Checked term fields, as wp_insert_term() and wp_update_term() take them.
+ */
+ private function stage_term_args( \WP_Term $term, array $args ): void {
+ $this->term_args = $args;
+ foreach ( $args as $field => $value ) {
+ $term->$field = $value;
+ }
+ }
+
+ /**
+ * Create or update the term, then give the object its stored values, so syncs get the term ID and the final slug.
+ *
+ * @param \WP_Term $subject Term.
+ * @return null|\WP_Error
+ */
+ protected function save( $subject ) {
+ $code = $subject->term_id > 0 ? 'woocommerce_ability_product_term_update_failed' : 'woocommerce_ability_product_term_create_failed';
+ $args = $this->term_args;
+ if ( 0 === $subject->term_id ) {
+ $name = $args['name'] ?? '';
+ unset( $args['name'] );
+ $result = wp_insert_term( wp_slash( $name ), $subject->taxonomy, wp_slash( $args ) );
+ } elseif ( ! empty( $args ) ) {
+ $result = wp_update_term( $subject->term_id, $subject->taxonomy, wp_slash( $args ) );
+ } else {
+ // The call only sent extension fields, which the syncs write.
+ $result = array( 'term_id' => $subject->term_id );
+ }
+ if ( is_wp_error( $result ) ) {
+ return new \WP_Error( $code, $result->get_error_message(), array( 'status' => 500 ) );
+ }
+
+ $subject->term_id = (int) $result['term_id'];
+ $stored = get_term( $subject->term_id, $subject->taxonomy );
+ if ( ! $stored instanceof \WP_Term ) {
+ return new \WP_Error( $code, __( 'The term was saved but could not be read back.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+ foreach ( get_object_vars( $stored ) as $field => $value ) {
+ $subject->$field = $value;
+ }
+ return null;
+ }
+
+ /**
+ * Return the saved term.
+ *
+ * @param \WP_Term $subject Saved term.
+ * @return array|\WP_Error
+ */
+ protected function prepare_response( $subject ) {
+ $output = self::format_term( $subject );
+ return is_wp_error( $output ) ? $output : array( 'term' => $output );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php
index 5a168585458..1ce3c63327b 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php
@@ -19,6 +19,14 @@ class CouponsQueryTest extends \WC_Unit_Test_Case {
use ExtensibleAbilitiesTestTrait;
+ /**
+ * Start each test with Core's resources registered, so the write abilities can read the ID of a coupon.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->isolate_extensible_abilities();
+ }
+
/**
* @testdox Should find scheduled coupons by code with their email restrictions.
*/
@@ -322,7 +330,6 @@ class CouponsQueryTest extends \WC_Unit_Test_Case {
*/
public function test_update_with_extension_fields(): void {
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
- add_action( 'woocommerce_extensible_abilities_resources_init', static fn() => ExtensibleAbilities::register_resource( 'coupon' ) );
$this->enable_extensible_abilities(
static function () {
ExtensibleAbilities::register_field(
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
index 6d6386eea95..457f61babd3 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderCreateTest.php
@@ -23,6 +23,7 @@ class OrderCreateTest extends WC_Unit_Test_Case {
public function setUp(): void {
parent::setUp();
+ $this->isolate_extensible_abilities();
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
index ebcbd5c5abf..c0b58e86bd7 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
@@ -23,6 +23,7 @@ class OrderUpdateTest extends WC_Unit_Test_Case {
public function setUp(): void {
parent::setUp();
+ $this->isolate_extensible_abilities();
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributeCreateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributeCreateTest.php
index 80bf3a32f42..68e1d05306e 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributeCreateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributeCreateTest.php
@@ -11,6 +11,7 @@ use Automattic\WooCommerce\Internal\Abilities\Ability;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductAttributeCreate;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductCreate;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductAttributesQuery;
+use Automattic\WooCommerce\Tests\Internal\Abilities\ExtensibleAbilitiesTestTrait;
use WC_Unit_Test_Case;
/**
@@ -18,6 +19,8 @@ use WC_Unit_Test_Case;
*/
class ProductAttributeCreateTest extends WC_Unit_Test_Case {
+ use ExtensibleAbilitiesTestTrait;
+
/**
* The System Under Test.
*
@@ -54,6 +57,7 @@ class ProductAttributeCreateTest extends WC_Unit_Test_Case {
public function setUp(): void {
parent::setUp();
$this->taxonomies_before = get_taxonomies();
+ $this->isolate_extensible_abilities();
update_option( 'woocommerce_feature_extensible_abilities_enabled', 'no' );
$this->sut = new Ability( ProductAttributeCreate::get_name(), ProductAttributeCreate::get_registration_args() );
wp_set_current_user( self::$administrator_id );
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
index 108282c77f3..4abb986199e 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermWritesTest.php
@@ -671,6 +671,115 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
$this->assertSame( 'Clearance', get_term( $id, 'product_tag' )->name );
}
+ /**
+ * @testdox Should write a sent extension field of a new and of an existing term in a sync, and save nothing when a validator or a sync refuses or the field does not apply to the taxonomy.
+ */
+ public function test_writes_extension_fields(): void {
+ $id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'name' => 'Existing',
+ )
+ );
+ update_option( 'woocommerce_feature_extensible_abilities_enabled', 'yes' );
+ $this->enable_extensible_abilities(
+ static function () {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => 'product_term',
+ 'namespace' => 'test-ext',
+ 'field' => 'label',
+ 'object_types' => array( 'product_tag' ),
+ 'output_schema' => array( 'type' => 'string' ),
+ 'input_schema' => array( 'type' => 'string' ),
+ 'get_callback' => static function ( \WP_Term $term ) {
+ $label = get_term_meta( $term->term_id, '_test_label', true );
+ return '' === $label ? null : $label;
+ },
+ )
+ );
+ ExtensibleAbilities::register_validator(
+ array(
+ 'resource' => 'product_term',
+ 'namespace' => 'test-ext',
+ 'callback' => static fn( \WP_Term $term ) => 'Refused' === $term->name ? new \WP_Error( 'refused', 'This name is refused.' ) : null,
+ )
+ );
+ ExtensibleAbilities::register_sync(
+ array(
+ 'resource' => 'product_term',
+ 'namespace' => 'test-ext',
+ 'callback' => static function ( array $saved, array $context ) {
+ foreach ( $saved as $term ) {
+ $label = $context['fields'][ $term ]['label'] ?? null;
+ if ( 'fail' === $label ) {
+ return new \WP_Error( 'sync_failed', 'The sync failed.' );
+ }
+ if ( null !== $label ) {
+ update_term_meta( $term->term_id, '_test_label', $label );
+ }
+ }
+ return null;
+ },
+ )
+ );
+ }
+ );
+ $extensions = static fn( string $label ) => array( 'test-ext' => array( 'label' => $label ) );
+
+ $created = $this->create(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'name' => 'Sale',
+ 'extensions' => $extensions( 'new' ),
+ )
+ );
+ $updated = $this->update(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'id' => $id,
+ 'extensions' => $extensions( 'changed' ),
+ )
+ );
+ $refused = $this->update(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'id' => $id,
+ 'name' => 'Refused',
+ 'extensions' => $extensions( 'lost' ),
+ )
+ );
+ $rolled_back = $this->create(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'name' => 'Rolled back',
+ 'extensions' => $extensions( 'fail' ),
+ )
+ );
+ $other_type = $this->create(
+ array(
+ 'taxonomy' => 'product_cat',
+ 'name' => 'Other taxonomy',
+ 'extensions' => $extensions( 'new' ),
+ )
+ );
+
+ $this->assertSame( 'new', $created['term']['extensions']['test-ext']['label'] );
+ $this->assertSame( 'new', get_term_meta( $created['term']['id'], '_test_label', true ) );
+ $this->assertSame( 'changed', $updated['term']['extensions']['test-ext']['label'] );
+ $this->assertSame( 'Existing', $updated['term']['name'] );
+ $this->assertWPError( $refused );
+ $this->assertSame( 'test-ext:refused', $refused->get_error_code() );
+ $this->assertSame( 'Existing', get_term( $id, 'product_tag' )->name );
+ $this->assertSame( 'changed', get_term_meta( $id, '_test_label', true ) );
+ $this->assertWPError( $rolled_back );
+ $this->assertSame( 'sync_failed', $rolled_back->get_error_code() );
+ $this->assertFalse( get_term_by( 'name', 'Rolled back', 'product_tag' ) );
+ $this->assertWPError( $other_type );
+ $this->assertSame( 'test-ext:woocommerce_ability_field_object_type', $other_type->get_error_code() );
+ $this->assertFalse( get_term_by( 'name', 'Other taxonomy', 'product_cat' ) );
+ }
+
/**
* Run the create ability.
*
@@ -678,7 +787,7 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
* @return mixed
*/
private function create( array $input ) {
- return ( new Ability( ProductTermCreate::get_name(), ProductTermCreate::get_registration_args() ) )->execute( $input );
+ return ( new ProductTermCreate( ProductTermCreate::ABILITY_NAME, ProductTermCreate::get_registration_args() ) )->execute( $input );
}
/**
@@ -688,6 +797,6 @@ class ProductTermWritesTest extends WC_Unit_Test_Case {
* @return mixed
*/
private function update( array $input ) {
- return ( new Ability( ProductTermUpdate::get_name(), ProductTermUpdate::get_registration_args() ) )->execute( $input );
+ return ( new ProductTermUpdate( ProductTermUpdate::ABILITY_NAME, ProductTermUpdate::get_registration_args() ) )->execute( $input );
}
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermsQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermsQueryTest.php
index f0cd185a141..e6eb86fdb59 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermsQueryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductTermsQueryTest.php
@@ -569,6 +569,72 @@ class ProductTermsQueryTest extends \WC_Unit_Test_Case {
$this->assertSame( $schema, ProductTermsQuery::get_registration_args()['output_schema'] );
}
+ /**
+ * @testdox Should apply the term meta, include and exclude clauses of extension filters to the terms and the total.
+ */
+ public function test_extension_filters(): void {
+ list( $first, $second, $third ) = self::factory()->term->create_many( 3, array( 'taxonomy' => 'product_tag' ) );
+ add_term_meta( $first, '_test_flag', '1' );
+ add_term_meta( $first, '_test_flag', '2' );
+ add_term_meta( $second, '_test_flag', '1' );
+ update_option( 'woocommerce_feature_extensible_abilities_enabled', 'yes' );
+ $this->enable_extensible_abilities(
+ static function () {
+ $filters = array(
+ 'flagged' => static fn() => array(
+ 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- The filter under test returns a term meta clause.
+ 'key' => '_test_flag',
+ 'compare' => 'EXISTS',
+ ),
+ ),
+ 'only' => static fn( array $ids ) => array( 'include_ids' => $ids ),
+ 'not' => static fn( array $ids ) => array( 'exclude_ids' => $ids ),
+ );
+ foreach ( $filters as $filter => $callback ) {
+ ExtensibleAbilities::register_query_filter(
+ array(
+ 'resource' => 'product_term',
+ 'namespace' => 'test-ext',
+ 'filter' => $filter,
+ 'schema' => 'flagged' === $filter ? array( 'type' => 'boolean' ) : array(
+ 'type' => 'array',
+ 'items' => array( 'type' => 'integer' ),
+ ),
+ 'callback' => $callback,
+ )
+ );
+ }
+ }
+ );
+ $ability = new Ability( ProductTermsQuery::get_name(), ProductTermsQuery::get_registration_args() );
+ $query = static function ( array $filters, array $input = array() ) use ( $ability ) {
+ $result = $ability->execute(
+ array_merge(
+ array(
+ 'taxonomy' => 'product_tag',
+ 'orderby' => 'id',
+ 'filters' => array( 'extensions' => array( 'test-ext' => $filters ) ),
+ ),
+ $input
+ )
+ );
+ return array( array_column( $result['terms'], 'id' ), $result['total'] );
+ };
+
+ $this->assertSame(
+ array( array( $first ), 1 ),
+ $query(
+ array(
+ 'flagged' => true,
+ 'not' => array( $second ),
+ )
+ )
+ );
+ $this->assertSame( array( array( $third ), 1 ), $query( array( 'only' => array( $second, $third ) ), array( 'include' => array( $first, $third ) ) ) );
+ $this->assertSame( array( array(), 0 ), $query( array( 'not' => array( $first ) ), array( 'include' => array( $first ) ) ) );
+ $this->assertSame( array( array( $third ), 1 ), $query( array( 'only' => array( $second, $third ) ), array( 'exclude' => array( $second ) ) ), 'The request exclude applies to the include of a filter.' );
+ }
+
/**
* Product categories the ability returns for a search.
*
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/ExtensibleAbilitiesTestTrait.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/ExtensibleAbilitiesTestTrait.php
index fb9579b5d24..0943636916a 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/ExtensibleAbilitiesTestTrait.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/ExtensibleAbilitiesTestTrait.php
@@ -20,7 +20,8 @@ trait ExtensibleAbilitiesTestTrait {
private ?array $extensible_abilities_before = null;
/**
- * Empty the registries of ExtensibleAbilities, so the test starts without resources and fields.
+ * Empty the registries of ExtensibleAbilities, so the test starts with Core's resources and without fields.
+ * The resources are also registered with the feature off, because a write reads the ID of an object from its resource.
*/
private function isolate_extensible_abilities(): void {
$registries = array();
@@ -31,6 +32,10 @@ trait ExtensibleAbilitiesTestTrait {
$property->setValue( null, array() );
}
$this->extensible_abilities_before ??= $registries;
+
+ add_action( 'woocommerce_extensible_abilities_resources_init', array( AbilitiesLoader::class, 'register_core_resources' ), 0 );
+ // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Documented in AbilitiesLoader::init_extensions().
+ do_action( 'woocommerce_extensible_abilities_resources_init' );
}
/**
@@ -42,14 +47,11 @@ trait ExtensibleAbilitiesTestTrait {
$this->isolate_extensible_abilities();
update_option( 'woocommerce_feature_' . ExtensibleAbilities::FEATURE_ID . '_enabled', 'yes' );
- add_action( 'woocommerce_extensible_abilities_resources_init', array( AbilitiesLoader::class, 'register_core_resources' ), 0 );
if ( $register ) {
add_action( 'woocommerce_extensible_abilities_init', $register );
}
- // phpcs:disable WooCommerce.Commenting.CommentHooks.MissingHookComment -- Documented in AbilitiesLoader::init_extensions().
- do_action( 'woocommerce_extensible_abilities_resources_init' );
+ // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Documented in AbilitiesLoader::init_extensions().
do_action( 'woocommerce_extensible_abilities_init' );
- // phpcs:enable
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index cc4642fa96b..b10bde69fee 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -16,6 +16,7 @@ use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
use Automattic\WooCommerce\Internal\DataStores\Orders\DataSynchronizer;
use Automattic\WooCommerce\RestApi\UnitTests\Helpers\OrderHelper;
use Automattic\WooCommerce\RestApi\UnitTests\HPOSToggleTrait;
+use Automattic\WooCommerce\Tests\Internal\Abilities\ExtensibleAbilitiesTestTrait;
use Automattic\WooCommerce\Utilities\OrderUtil;
/**
@@ -23,6 +24,7 @@ use Automattic\WooCommerce\Utilities\OrderUtil;
*/
class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
+ use ExtensibleAbilitiesTestTrait;
use HPOSToggleTrait;
private const CODE_SCHEMA = array(
@@ -852,7 +854,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertSame( array(), ExtensibleAbilities::get_query_args( 'ticket', $input ) );
$register_resource = static function () {
- ExtensibleAbilities::register_resource( 'ticket' );
+ ExtensibleAbilities::register_resource( 'ticket', self::get_ticket_resource_args() );
};
$register = static function () use ( $filter ) {
ExtensibleAbilities::register_query_filter( $filter );
@@ -1228,7 +1230,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$resources = new \ReflectionProperty( ExtensibleAbilities::class, 'resources' );
$resources->setAccessible( true );
- $covered = array_merge( array_keys( $this->provide_list_abilities() ), array( 'order', 'order_item' ) );
+ $covered = array_merge( array_keys( $this->provide_list_abilities() ), array( 'order', 'order_item', 'coupon' ) );
$this->assertEqualsCanonicalizing( array_keys( $resources->getValue() ), $covered, 'Add the new resource to provide_list_abilities().' );
}
@@ -1465,7 +1467,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
*/
public function test_register_resource_lets_an_extension_register_fields_on_its_own_resource(): void {
$register_resource = static function () {
- ExtensibleAbilities::register_resource( 'ticket' );
+ ExtensibleAbilities::register_resource( 'ticket', self::get_ticket_resource_args() );
};
$register_field = static function () {
ExtensibleAbilities::register_field(
@@ -1498,7 +1500,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_resource' );
$this->get_output_schema( 'woocommerce/products-query' );
- ExtensibleAbilities::register_resource( 'late_resource' );
+ ExtensibleAbilities::register_resource( 'late_resource', self::get_ticket_resource_args() );
$this->assertFalse( ExtensibleAbilities::is_resource_registered( 'late_resource' ) );
}
@@ -1685,7 +1687,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
public function test_a_resource_name_of_only_digits_is_refused(): void {
$this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_resource' );
- ExtensibleAbilities::register_resource( '42' );
+ ExtensibleAbilities::register_resource( '42', self::get_ticket_resource_args() );
$resources = new \ReflectionProperty( ExtensibleAbilities::class, 'resources' );
$resources->setAccessible( true );
@@ -1736,7 +1738,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
)
)['orders'];
- $this->assertSame( 0, did_action( 'woocommerce_extensible_abilities_resources_init' ) );
+ $this->assertTrue( ExtensibleAbilities::is_resource_registered( 'product' ), 'A write reads the ID of an object from its resource, also with the feature off.' );
$this->assertSame( 0, did_action( 'woocommerce_extensible_abilities_init' ) );
$this->assertArrayNotHasKey( 'filters', $this->get_ability( 'woocommerce/products-query' )['input_schema']['properties'] );
$this->assertSame( 400, $this->run_ability_response( 'woocommerce/products-query', array( 'filters' => array( 'extensions' => array( 'test-ext' => array( 'has_code' => true ) ) ) ) )->get_status() );
@@ -4891,10 +4893,15 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
}
/**
- * @testdox Should refuse the call and save nothing when a secondary object names a resource that is not registered.
+ * @testdox Should refuse the call and save nothing when a secondary object names a resource that is not registered, with the feature on or off.
+ * @testWith [true]
+ * [false]
+ *
+ * @param bool $enabled Whether the feature is on.
*/
- public function test_a_secondary_object_with_an_unregistered_resource_is_refused(): void {
+ public function test_a_secondary_object_with_an_unregistered_resource_is_refused( bool $enabled ): void {
$this->setExpectedIncorrectUsage( TestProductWithItemAbility::class . '::change' );
+ $this->set_feature( $enabled );
$this->register_product_with_item_ability();
TestProductWithItemAbility::$item_resource = 'refund';
$product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
@@ -5213,10 +5220,52 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertSame( 'Pen', wc_get_product( $product->get_id() )->get_name() );
}
+ /**
+ * @testdox Should refuse the call and save nothing when the resource of the ability is not registered, with the feature off.
+ */
+ public function test_an_ability_with_an_unregistered_resource_is_refused(): void {
+ $this->set_feature( false );
+ $product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
+ $ability = new class(
+ 'test-ext/ticket-rename',
+ array(
+ 'label' => 'Rename ticket',
+ 'description' => 'Renames a ticket product.',
+ 'category' => 'woocommerce',
+ 'output_schema' => array( 'type' => 'object' ),
+ 'permission_callback' => '__return_true',
+ )
+ ) extends TestProductRenameAbility {
+ /**
+ * A resource that is not registered.
+ *
+ * @return string
+ */
+ public function get_resource(): string {
+ return 'ticket';
+ }
+
+ };
+ $this->setExpectedIncorrectUsage( get_class( $ability ) . '::get_resource' );
+
+ $result = $ability->execute_change(
+ array(
+ 'id' => $product->get_id(),
+ 'name' => 'Pencil',
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_resource_unknown', $result->get_error_code() );
+ $this->assertSame( 'ticket', $result->get_error_data()['resource'] );
+ $this->assertSame( 'Pen', wc_get_product( $product->get_id() )->get_name() );
+ }
+
/**
* @testdox Should save nothing when change() returns a WP_Error without errors.
*/
public function test_an_empty_error_from_change_saves_nothing(): void {
+ $this->isolate_extensible_abilities();
$product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
$ability = new class(
'test-ext/product-rename',
@@ -5456,6 +5505,152 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertArrayNotHasKey( 'plan', $read['products'][0]['extensions']['test-ext'] ?? array() );
}
+ /**
+ * @testdox Should limit a term field with object_types to the terms of those taxonomies.
+ */
+ public function test_object_types_limit_a_term_field_to_some_taxonomies(): void {
+ $this->register_typed_field( 'product_term', array( 'product_brand' ) );
+ $list_terms = fn( string $taxonomy ): array => $this->run_ability(
+ 'woocommerce/product-terms-query',
+ array(
+ 'taxonomy' => $taxonomy,
+ 'include' => array( self::factory()->term->create( array( 'taxonomy' => $taxonomy ) ) ),
+ 'hide_empty' => false,
+ )
+ )['terms'];
+
+ $brands = $list_terms( 'product_brand' );
+ $categories = $list_terms( 'product_cat' );
+
+ $this->assertSame( 'value', $brands[0]['extensions']['test-ext']['typed'] );
+ $this->assertCount( 1, $categories );
+ $this->assertArrayNotHasKey( 'extensions', $categories[0] );
+ }
+
+ /**
+ * @testdox Should limit a coupon field with object_types to the coupons of those discount types.
+ */
+ public function test_object_types_limit_a_coupon_field_to_some_discount_types(): void {
+ $this->register_typed_field( 'coupon', array( 'percent' ) );
+ $this->get_output_schema( 'woocommerce/products-query' );
+ $read = static function ( string $discount_type ) {
+ $coupon = new \WC_Coupon();
+ $coupon->set_discount_type( $discount_type );
+ return ExtensibleAbilities::add_fields_to_object( array(), 'coupon', $coupon );
+ };
+
+ $this->assertSame( array( 'test-ext' => array( 'typed' => 'value' ) ), $read( 'percent' )['extensions'] );
+ $this->assertSame( array(), $read( 'fixed_cart' ) );
+ }
+
+ /**
+ * @testdox Should compare the object_types of a $resource_name field with the type that the resource gives.
+ * @dataProvider provide_resources_with_their_object_type
+ *
+ * @param string $resource_name Resource.
+ * @param string $ability List ability.
+ * @param string $list_key Output key of the list.
+ * @param callable $create_input Creates two objects and returns the ability input that lists them.
+ * @param string $object_type The type of the created objects.
+ */
+ public function test_object_types_compare_with_the_type_of_the_resource( string $resource_name, string $ability, string $list_key, callable $create_input, string $object_type ): void {
+ $this->register_typed_field( $resource_name, array( $object_type ) );
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_init',
+ static function () use ( $resource_name ) {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => $resource_name,
+ 'namespace' => 'test-ext',
+ 'field' => 'other',
+ 'output_schema' => array( 'type' => 'string' ),
+ 'object_types' => array( 'another-type' ),
+ 'get_callback' => static fn() => 'value',
+ )
+ );
+ }
+ );
+
+ $list = $this->run_ability( $ability, $create_input() )[ $list_key ];
+
+ $this->assertCount( 2, $list );
+ $this->assertSame( array( 'typed' => 'value' ), $list[0]['extensions']['test-ext'] );
+ }
+
+ /**
+ * The rows of provide_list_abilities() for a customer and a review, with the type of the objects they create:
+ * the user role and the comment type.
+ *
+ * @return array<string, array>
+ */
+ public function provide_resources_with_their_object_type(): array {
+ $rows = $this->provide_list_abilities();
+ return array(
+ 'customer' => array_merge( $rows['customer'], array( 'customer' ) ),
+ 'product_review' => array_merge( $rows['product_review'], array( 'review' ) ),
+ );
+ }
+
+ /**
+ * @testdox Should refuse a resource that has no callable $missing.
+ * @testWith ["object_id_callback"]
+ * ["object_type_callback"]
+ *
+ * @param string $missing The argument the resource does not pass.
+ */
+ public function test_a_resource_without_both_callbacks_is_refused( string $missing ): void {
+ $this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_resource' );
+
+ ExtensibleAbilities::register_resource( 'ticket', array_diff_key( self::get_ticket_resource_args(), array( $missing => true ) ) );
+
+ $this->assertFalse( ExtensibleAbilities::is_resource_registered( 'ticket' ) );
+ }
+
+ /**
+ * @testdox Should throw when the ID of an object is read from a resource that is not registered.
+ */
+ public function test_the_id_of_an_object_of_an_unregistered_resource_throws(): void {
+ $this->expectException( \LogicException::class );
+
+ ExtensibleAbilities::get_object_id( new \stdClass(), 'gadget' );
+ }
+
+ /**
+ * The callbacks of a test resource whose objects have an `id` and one type.
+ *
+ * @return array<string, callable>
+ */
+ private static function get_ticket_resource_args(): array {
+ return array(
+ 'object_id_callback' => static fn( $ticket ): int => (int) ( $ticket->id ?? 0 ),
+ 'object_type_callback' => static fn(): string => 'ticket',
+ );
+ }
+
+ /**
+ * Register a readable `test-ext.typed` field with object_types.
+ *
+ * @param string $resource_name Resource of the field.
+ * @param string[] $object_types Object types the field applies to.
+ */
+ private function register_typed_field( string $resource_name, array $object_types ): void {
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_init',
+ static function () use ( $resource_name, $object_types ) {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => $resource_name,
+ 'namespace' => 'test-ext',
+ 'field' => 'typed',
+ 'output_schema' => array( 'type' => 'string' ),
+ 'object_types' => $object_types,
+ 'get_callback' => static fn() => 'value',
+ )
+ );
+ }
+ );
+ }
+
/**
* @testdox Should list in the variation schemas only the fields that can apply to a variation.
*/