Commit 0c2596405ea for woocommerce
commit 0c2596405ea306623ffa1e74ddf4966f758c3908
Author: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com>
Date: Wed Nov 25 12:53:00 2026 -0300
Give validators and syncs the field values the call sent (#71369)
* Give validators and syncs the field values the call sent
Validators and syncs get $context['fields'], keyed by object, with the
fields of their own namespace that the call sent. Syncs no longer get
the input, and they get only the saved objects of their own resource.
The ability argument is removed; the context holds the ability name.
A set_callback is optional: a field is writable when it declares
input_schema.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Read the sent fields without the deprecated SplObjectStorage::contains()
PHP 8.5 deprecates SplObjectStorage::contains(). The lookup now calls
offsetExists(), which does the same check on every supported PHP version.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Assert the sent null value strictly in the sent fields test
assertEquals() also accepts an empty string in place of null.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/plugins/woocommerce/changelog/wooai-1748-sent-fields-for-validators-and-syncs b/plugins/woocommerce/changelog/wooai-1748-sent-fields-for-validators-and-syncs
new file mode 100644
index 00000000000..b46837325e0
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1748-sent-fields-for-validators-and-syncs
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Change what extensible abilities validators and syncs receive; the feature is experimental and off by default.
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index 044bb5943d1..43647c96675 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -18,7 +18,7 @@ defined( 'ABSPATH' ) || exit;
* and saves them in one call. Register it with a subclass as the
* `ability_class`. The execute callback loads the primary object, checks the
* `extensions` input against the field input schemas, changes the objects in memory,
- * writes the fields with their `set_callback`, runs the validators that
+ * writes the fields that have a `set_callback`, runs the validators that
* ExtensibleAbilities::register_validator() adds, saves, and then prepares the
* response. A rejection before the save saves nothing. When prepare_response()
* returns a WP_Error, the change is already saved, so the error message names
@@ -44,8 +44,8 @@ defined( 'ABSPATH' ) || exit;
* still inside the transaction, the syncs that ExtensibleAbilities::register_sync()
* adds write what the saved objects imply elsewhere, such as the price range a
* variable parent derives from its variations, or a row in a table of the
- * extension. A sync also sees the objects the call deleted and the input of
- * the call. A refusal there rolls the call back too. When a query hits a
+ * extension. A sync also sees the objects the call deleted and the field
+ * values the call sent. A refusal there rolls the call back too. When a query hits a
* deadlock, a lock wait timeout or a snapshot conflict with a parallel call, the call rolls
* back and fails with a WP_Error instead of reporting the write. A rollback drops the
* object caches of the objects the call saved or deleted. It does not undo what a sync
@@ -257,8 +257,9 @@ abstract class ActionableAbility extends Ability {
$objects[] = array( $secondary[0], $fields, $resource_name );
}
+ $sent = array();
foreach ( $objects as list( $object, $fields ) ) {
- $this->apply_fields( $object, $fields, $refused );
+ $this->apply_fields( $object, $fields, $sent, $refused );
}
$deleting = $core_refused ? array() : $this->get_objects_to_delete();
@@ -274,11 +275,13 @@ abstract class ActionableAbility extends Ability {
$object,
$resource_name,
array(
+ 'ability' => $this->get_name(),
'primary' => $subject,
'deleting' => in_array( $object, $deleting, true ),
'objects' => $staged,
'objects_to_delete' => $deleting,
),
+ $sent,
$refused
);
}
@@ -288,9 +291,9 @@ abstract class ActionableAbility extends Ability {
try {
$saved = DatabaseTransaction::run(
- function () use ( $subject, $objects, $input, $enabled ) {
+ function () use ( $subject, $objects, $sent, $enabled ) {
$saved = $this->save( $subject );
- return ! is_wp_error( $saved ) && $enabled ? $this->sync( $objects, $input ) : $saved;
+ return ! is_wp_error( $saved ) && $enabled ? $this->sync( $objects, $sent ) : $saved;
}
);
} catch ( \Throwable $e ) {
@@ -312,35 +315,38 @@ abstract class ActionableAbility extends Ability {
/**
* Run the syncs of each resource that the call saved or deleted, once,
- * after the last save and before the commit. A deleted or trashed object
- * is not in the saved list, even when it was the primary object.
+ * 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 $input Ability input.
+ * @param array<int, array{0: \WC_Data, 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 $input ): ?\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 ) );
- $saved = array_values(
- array_filter(
- array_column( $objects, 0 ),
- static fn( $item ) => $item->get_id() > 0 && ! in_array( get_class( $item ) . ':' . $item->get_id(), $gone, true )
- )
- );
- $resources = array_column( $objects, 2 );
- if ( ! empty( $deleted ) || ! empty( $trashed ) ) {
- $resources[] = $this->get_resource();
+ 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 ) );
+ $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 ) ) {
+ $saved[] = $object;
+ $own[ $resource_name ][] = $object;
+ }
}
$context = array(
+ 'ability' => $this->get_name(),
+ 'primary' => $objects[0][0],
+ 'objects' => $saved,
'deleted' => array_values( $deleted ),
'trashed' => array_values( $trashed ),
- 'input' => $input,
);
- foreach ( array_unique( $resources ) as $resource_name ) {
+ foreach ( $own as $resource_name => $resource_saved ) {
foreach ( ExtensibleAbilities::get_syncs( $resource_name ) as $args ) {
- $rejected = self::run_callback( $args['callback'], array( $saved, $this, $context ), array( 'namespace' => $args['namespace'] ) );
+ $context['fields'] = self::get_sent_fields( $sent, $args['namespace'] );
+ $rejected = self::run_callback( $args['callback'], array( $resource_saved, $context ), array( 'namespace' => $args['namespace'] ) );
if ( null !== $rejected ) {
return $rejected;
}
@@ -449,7 +455,7 @@ abstract class ActionableAbility extends Ability {
$args = $candidates[ $field ] ?? null;
if ( null === $args ) {
$refusals[] = self::describe_unknown_field( $candidates, (string) $namespace, (string) $field );
- } elseif ( ! isset( $args['set_callback'] ) ) {
+ } elseif ( ! isset( $args['input_schema'] ) ) {
/* translators: 1: Extension namespace. 2: Field name. */
$refusals[] = sprintf( __( 'The extension field "%1$s.%2$s" is read-only. Remove it from the input.', 'woocommerce' ), $namespace, $field );
} else {
@@ -491,7 +497,7 @@ abstract class ActionableAbility extends Ability {
* @return string
*/
private static function describe_unknown_field( array $fields, string $extension_namespace, string $field ): string {
- $writable = array_keys( array_filter( $fields, static fn( array $args ): bool => isset( $args['set_callback'] ) ) );
+ $writable = array_keys( array_filter( $fields, static fn( array $args ): bool => isset( $args['input_schema'] ) ) );
if ( empty( $writable ) ) {
/* translators: 1: Extension namespace. 2: Field name. */
return sprintf( __( 'The extension namespace "%1$s" has no field "%2$s", and it has no fields you can write. Remove "%1$s.%2$s" from the input.', 'woocommerce' ), $extension_namespace, $field );
@@ -530,7 +536,7 @@ abstract class ActionableAbility extends Ability {
foreach ( $values as $namespace => $fields ) {
foreach ( (array) $fields as $field => $value ) {
$args = $registered[ $namespace ][ $field ] ?? array();
- if ( ! isset( $args['set_callback'] ) ) {
+ if ( ! isset( $args['input_schema'] ) ) {
return new \WP_Error(
'woocommerce_ability_field_not_writable',
/* translators: 1: Extension namespace. 2: Field name. */
@@ -555,14 +561,16 @@ abstract class ActionableAbility extends Ability {
/**
* Write the checked values to the object in memory with the set_callback
- * of each field, also after one rejects its value. Each rejection goes into
- * the given errors, as add_refusal() describes.
- *
- * @param \WC_Data $subject Object to change.
- * @param array $updates Pairs of field arguments and value from prepare_fields().
- * @param \WP_Error $refused Collects the refusals, including a field that does not apply to the object.
+ * of each field that has one, also after one rejects its value. Each
+ * 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 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.
*/
- private function apply_fields( $subject, array $updates, \WP_Error $refused ): void {
+ private function apply_fields( $subject, array $updates, array &$sent, \WP_Error $refused ): void {
foreach ( $updates as $param => list( $args, $value ) ) {
if ( ! ExtensibleAbilities::field_applies_to( $args, $subject ) ) {
$rejected = new \WP_Error(
@@ -577,26 +585,58 @@ abstract class ActionableAbility extends Ability {
array( 'status' => 400 )
);
} else {
- $rejected = self::run_callback( $args['set_callback'], array( $subject, $value ), array( 'field' => $param ) );
+ $rejected = isset( $args['set_callback'] ) ? self::run_callback( $args['set_callback'], array( $subject, $value ), array( 'field' => $param ) ) : null;
}
+ list( , $namespace, $field ) = explode( '.', $param, 3 );
if ( null !== $rejected ) {
- self::add_refusal( $rejected, explode( '.', $param )[1], $refused );
+ self::add_refusal( $rejected, $namespace, $refused );
+ } else {
+ $fields = self::get_sent_fields( $sent, $namespace );
+ $fields[ $subject ] = $fields[ $subject ] + array( $field => $value );
}
}
}
+ /**
+ * The `fields` context of one namespace: a map from each object of the call
+ * to the `field => value` pairs that the call sent for it in that namespace.
+ * It gives an empty array for any other object. PHP 7.4 has no WeakMap, so
+ * the map is an SplObjectStorage.
+ *
+ * @param array<string, \SplObjectStorage<object, array<string, mixed>>> $sent The maps of the call, keyed by namespace. A missing one is added.
+ * @param string $extension Namespace of the field or callback.
+ * @return \SplObjectStorage<object, array<string, mixed>>
+ */
+ private static function get_sent_fields( array &$sent, string $extension ): \SplObjectStorage {
+ $sent[ $extension ] ??= new class() extends \SplObjectStorage {
+ /**
+ * The sent fields of an object, or an empty array.
+ *
+ * @param object $subject Object.
+ * @return array
+ */
+ #[\ReturnTypeWillChange]
+ public function offsetGet( $subject ) {
+ return parent::offsetExists( $subject ) ? parent::offsetGet( $subject ) : array();
+ }
+ };
+ return $sent[ $extension ];
+ }
+
/**
* 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 string $resource_name Resource of the object.
- * @param array $context 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 \WP_Error $refused Collects the refusals.
+ * @param \WC_Data $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().
+ * @param \WP_Error $refused Collects the refusals.
*/
- private function validate( $subject, string $resource_name, array $context, \WP_Error $refused ): void {
+ private function validate( $subject, string $resource_name, array $context, array $sent, \WP_Error $refused ): void {
foreach ( ExtensibleAbilities::get_validators( $resource_name ) as $args ) {
- $rejected = self::run_callback( $args['callback'], array( $subject, $this, $context ), array( 'namespace' => $args['namespace'] ) );
+ $context['fields'] = self::get_sent_fields( $sent, $args['namespace'] );
+ $rejected = self::run_callback( $args['callback'], array( $subject, $context ), array( 'namespace' => $args['namespace'] ) );
if ( null !== $rejected ) {
self::add_refusal( $rejected, $args['namespace'], $refused );
}
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index d3f3d3d9311..e37d9291103 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -21,7 +21,7 @@ defined( 'ABSPATH' ) || exit;
* object of that resource returns the field values under
* `extensions.<namespace>.<field>`, and lists the fields in its output schema.
* An ActionableAbility writes the same `extensions` input to the fields that
- * have a `set_callback`, runs the validators of the resource, and saves
+ * have an `input_schema`, runs the validators of the resource, and saves
* the object one time.
* An extension also registers a query filter, which the list ability of the
* resource accepts under `filters.extensions.<namespace>.<filter>`.
@@ -128,8 +128,13 @@ class ExtensibleAbilities {
*
* Call it inside the `woocommerce_extensible_abilities_init` action. A call after that action is refused.
* The resource must be registered with `register_resource()` in the earlier `woocommerce_extensible_abilities_resources_init` action.
- * A field declares `get_callback` and `output_schema`, `set_callback` and `input_schema`, or both pairs. The
- * first pair makes it readable and the second makes it writable. An incomplete pair is refused.
+ * 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
+ * `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']`.
*
* @since 11.3.0
*
@@ -166,18 +171,21 @@ class ExtensibleAbilities {
* callback must not return a list for an `object` or a `date-time` without
* a UTC offset: the schema check accepts them, and a strict client refuses
* the whole result.
- * @type array $input_schema Optional. JSON schema of the value that `set_callback` receives. It needs
+ * @type array $input_schema Optional. JSON schema of the value that the client sends. It makes the
+ * field writable. It needs
* one `type` name, or an `anyOf` where each branch has one `type` name. A
* list of types is refused, at the top level and in every nested schema under
* the keywords listed for `output_schema`, because some clients refuse it: a
* nullable value uses `[{"type":"string"},{"type":"null"}]` as its `anyOf`.
* Core publishes it as declared. A value can be null only where it declares
- * null. Required with `set_callback`.
+ * null.
* @type callable $set_callback Optional. Receives the object and the value, and changes the object
* in memory, when an ability creates or updates the object. It returns a
* WP_Error to reject the value, and then nothing is saved. It also runs
- * after Core refuses another value of the primary object. A field without
- * it cannot be written. Required with `input_schema`. Rules:
+ * after Core refuses another value of the primary object. It needs
+ * `input_schema`. Without it, Core only checks the value against
+ * `input_schema`, and validators and syncs read it from
+ * `$context['fields']`. Rules:
* 1. It only sets values in memory. It does not save, send email
* or make HTTP requests.
* 2. It receives the value already cast to `input_schema`.
@@ -227,7 +235,7 @@ class ExtensibleAbilities {
$readable = isset( $args['get_callback'] ) || isset( $args['output_schema'] );
$writable = isset( $args['set_callback'] ) || isset( $args['input_schema'] );
if ( ! $readable && ! $writable ) {
- wc_doing_it_wrong( __METHOD__, 'A field needs "get_callback" and "output_schema", "set_callback" and "input_schema", or both pairs.', '11.4.0' );
+ wc_doing_it_wrong( __METHOD__, 'A field needs "get_callback" and "output_schema", "input_schema", or both.', '11.4.0' );
return;
}
if ( $readable ) {
@@ -245,12 +253,12 @@ class ExtensibleAbilities {
}
}
if ( $writable ) {
- if ( ! is_callable( $args['set_callback'] ?? null ) ) {
- wc_doing_it_wrong( __METHOD__, 'The "set_callback" argument must be callable, and a field with an "input_schema" needs it.', '11.4.0' );
+ if ( isset( $args['set_callback'] ) && ! is_callable( $args['set_callback'] ) ) {
+ wc_doing_it_wrong( __METHOD__, 'The "set_callback" argument must be callable.', '11.4.0' );
return;
}
if ( ! is_array( $args['input_schema'] ?? null ) || ! self::input_schema_has_type( $args['input_schema'] ) ) {
- wc_doing_it_wrong( __METHOD__, 'The "input_schema" argument must be an array with one "type" name, or with an "anyOf" where each branch has one "type" name. For a nullable field, use an "anyOf" with a {"type":"null"} branch instead of a list of types.', '11.4.0' );
+ wc_doing_it_wrong( __METHOD__, 'A field with a "set_callback" needs an "input_schema". The "input_schema" argument must be an array with one "type" name, or with an "anyOf" where each branch has one "type" name. For a nullable field, use an "anyOf" with a {"type":"null"} branch instead of a list of types.', '11.4.0' );
return;
}
}
@@ -628,9 +636,10 @@ class ExtensibleAbilities {
*
* @type string $resource Resource that an ActionableAbility changes, such as `product`.
* @type string $namespace Slug of the extension that owns the validator, such as `subscriptions`.
- * @type callable $callback Receives the changed object, the ability and `array $context`, after Core's
- * changes and the field callbacks, before the one save. A callback that only
- * needs the object or the ability can take fewer arguments.
+ * @type callable $callback Receives the changed object and `array $context`, after Core's changes and
+ * the field callbacks, before the one save.
+ * `$context['ability']` is the name of the ability, such as
+ * `woocommerce/product-update`.
* `$context['primary']` is the primary object of the call. It differs from the
* changed object when the object is a variation that the call saves through
* its parent. On product-create that parent is not saved yet, so the variation
@@ -641,7 +650,11 @@ class ExtensibleAbilities {
* the primary object first, with the field writes of all of them applied, so
* a rule can compare a variation with the other variations of the same call.
* `$context['objects_to_delete']` is every object the call deletes or
- * trashes. It returns a WP_Error to refuse the change, and then nothing is
+ * trashes. `$context['fields']` is keyed by object: `$context['fields'][ $object ]`
+ * is the `field => value` pairs that the call sent for that object, as
+ * register_sync() describes. Read it for a value that no `set_callback`
+ * stores on the object. A validator checks the final state of the object,
+ * also when the call sent none of its fields. It returns a WP_Error to refuse the change, and then nothing is
* saved. The other validators still run, and the client gets every refusal in
* one error. The client sees the code prefixed with the namespace, as
* `<namespace>:<code>`. A code that another validator in the same namespace
@@ -654,8 +667,6 @@ class ExtensibleAbilities {
* their old values. Rules:
* 1. It only reads. It does not change the object, save, send email or
* make HTTP requests.
- * 2. It checks the ability name when the extension's own abilities
- * change the same resource.
* }
*/
public static function register_validator( array $args ): void {
@@ -678,8 +689,8 @@ class ExtensibleAbilities {
*
* A sync registered for a resource runs only when an object of that resource
* was saved, deleted or trashed in the call. It runs once per call, not once per
- * object. The saved objects can belong to more than one resource, so a sync
- * reads the objects it owns and ignores the rest.
+ * object. It can run with no saved objects when a call only deletes, and then
+ * it reads the deleted objects from the context.
*
* @since 11.4.0
*
@@ -688,15 +699,29 @@ 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`, the ActionableAbility and `array $context`.
- * `$saved` is every saved object of the call, the primary object first
- * unless the call deleted it.
+ * @type callable $callback Receives `\WC_Data[] $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
+ * `woocommerce/product-update`.
+ * `$context['primary']` is the primary object of the call, also when it
+ * belongs to another resource or the call deleted it.
+ * `$context['objects']` is every saved object of the call, of every
+ * resource, the primary object first unless the call deleted it.
* `$context['deleted']` is every object the call deleted for good, as it
* was before the delete, with its ID. `$context['trashed']` is every object
* the call moved to the trash; it can be restored, so a sync keeps what a
- * restore needs. And
- * `$context['input']` is the input of the call, so a sync can skip work
- * when the call did not write its fields. It returns a WP_Error to
+ * restore needs.
+ * `$context['fields']` is keyed by object: `$context['fields'][ $object ]`
+ * is the `field => value` pairs that the call sent for that object. It
+ * holds only the fields of the callback's own namespace. Each value is the
+ * sent value, cast to `input_schema` as the `set_callback` receives it, and
+ * not what the `set_callback` stored. A sent null is kept, so use
+ * `array_key_exists()` to tell "clear the value" from "not sent". A value
+ * that was refused is left out. An object that got no fields, or is not in
+ * the call, gives an empty array. A sync writes the data kept outside the
+ * object from here, for every saved object and not only the first.
+ * It returns a WP_Error to
* refuse, and then every save of the call is undone. A thrown exception
* refuses it too. The error gets the namespace in its data, and the 400
* status when it has no status, as a validator's error does. A sync must not
@@ -956,7 +981,7 @@ class ExtensibleAbilities {
/**
* The schema of the `extensions` input of a resource. It lists the fields
- * that have a set_callback, each with its input schema as declared, and says
+ * that have an input schema, each as declared, and says
* which object types a field with `object_types` applies to. ActionableAbility adds it to the input schema of every
* ability. An ability that writes other objects of the resource in the same
* call, such as the variations of a product, adds it to their input too.
@@ -977,7 +1002,7 @@ class ExtensibleAbilities {
$writable = array_filter(
null === $field_filter ? $fields : array_filter( $fields, $field_filter ),
static function ( array $args ): bool {
- return isset( $args['set_callback'] );
+ return isset( $args['input_schema'] );
}
);
if ( empty( $writable ) ) {
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 3caca2837b4..6335d0208f5 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -2305,13 +2305,11 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'schema' => array( 'type' => 'string' ),
),
array( 'set_callback' => '__return_null' ),
- array( 'input_schema' => array( 'type' => 'string' ) ),
array(
'set_callback' => 'not_a_function',
'input_schema' => array( 'type' => 'string' ),
),
$read + array( 'set_callback' => '__return_null' ),
- $read + array( 'input_schema' => array( 'type' => 'string' ) ),
$read + array(
'input_schema' => array( 'type' => 'string' ),
'set_callback' => 'not_a_function',
@@ -3510,8 +3508,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
'product',
'test-ext',
- static function ( array $saved, ActionableAbility $ability ) use ( &$calls ) {
- $calls[] = array( $ability->get_name(), array_map( 'get_class', $saved ), array_map( static fn( \WC_Data $saved_object ) => $saved_object->get_id(), $saved ) );
+ static function ( array $saved, array $context ) use ( &$calls ) {
+ $calls[] = array( $context['ability'], array_map( 'get_class', $saved ), array_map( static fn( \WC_Data $saved_object ) => $saved_object->get_id(), $saved ) );
$prices = array();
foreach ( $saved as $object ) {
if ( $object instanceof \WC_Product_Variation ) {
@@ -3536,19 +3534,18 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
}
/**
- * @testdox Should give a sync the deleted objects and the input of the call.
+ * @testdox Should give a sync the deleted and the trashed objects of the call.
*/
- public function test_a_sync_gets_the_deleted_objects_and_the_input(): void {
+ public function test_a_sync_gets_the_deleted_and_trashed_objects(): void {
$contexts = array();
$this->register_sync(
'product',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$contexts ) {
+ static function ( array $saved, array $context ) use ( &$contexts ) {
$contexts[] = array(
'saved' => array_map( static fn( \WC_Data $item ) => $item->get_id(), $saved ),
'deleted' => array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['deleted'] ),
'trashed' => array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['trashed'] ),
- 'input' => $context['input'],
);
return null;
}
@@ -3585,7 +3582,6 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertSame( array(), $contexts[0]['deleted'] );
$this->assertSame( array( $created['product']['id'] ), $contexts[1]['saved'] );
$this->assertSame( array( $created['product']['variation_ids'][1] ), $contexts[1]['deleted'] );
- $this->assertSame( $input, $contexts[1]['input'] );
$this->assertSame( array( $created['product']['id'] ), $contexts[2]['saved'], 'A variation delete saves the parent.' );
$this->assertSame( array( $created['product']['variation_ids'][0] ), $contexts[2]['deleted'] );
$this->assertSame( array(), $contexts[3]['saved'] );
@@ -3595,6 +3591,148 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertSame( array(), $contexts[4]['trashed'] );
}
+ /**
+ * Register `test-ext.vendor` on a resource: a writable field with no set_callback, as a field kept outside the object has.
+ *
+ * @param string $resource_name Resource.
+ */
+ private function register_vendor_field( string $resource_name ): void {
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_init',
+ static function () use ( $resource_name ) {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => $resource_name,
+ 'namespace' => 'test-ext',
+ 'field' => 'vendor',
+ 'input_schema' => self::nullable( array( 'type' => 'string' ) ),
+ )
+ );
+ }
+ );
+ }
+
+ /**
+ * @testdox Should give validators and syncs the sent fields of their own namespace for each object, with a sent null.
+ */
+ public function test_validators_and_syncs_get_the_sent_fields_of_each_object(): void {
+ $seen = array();
+ $record = static function ( string $step, array $objects, array $context ) use ( &$seen ) {
+ foreach ( $objects as $object ) {
+ $seen[ $step ][ $object->get_sku() ] = $context['fields'][ $object ];
+ }
+ $seen[ $step ]['other'] = $context['fields'][ new \WC_Product() ];
+ return null;
+ };
+ $this->register_validator( 'product', 'test-ext', static fn( \WC_Product $product, array $context ) => $record( 'validator', array( $product ), $context ) );
+ $this->register_sync( 'product', 'test-ext', static fn( array $saved, array $context ) => $record( 'sync', $saved, $context ) );
+ $this->register_vendor_field( 'product' );
+ $this->reset_registries();
+ $input = $this->get_shirt_input();
+ $input['sku'] = 'shirt';
+ $input['extensions'] = array(
+ 'test-ext' => array(
+ 'color' => 'blue',
+ 'vendor' => 'acme',
+ ),
+ 'other_ext' => array( 'size' => 'small' ),
+ );
+ $input['variations'][0]['extensions'] = array( 'test-ext' => array( 'vendor' => null ) );
+
+ $this->run_ability( 'woocommerce/product-create', $input );
+
+ $expected = array(
+ 'shirt' => array(
+ 'color' => 'blue',
+ 'vendor' => 'acme',
+ ),
+ 'other' => array(),
+ 'shirt-s' => array( 'vendor' => null ),
+ 'shirt-m' => array(),
+ );
+ $this->assertEquals( $expected, $seen['validator'] );
+ $this->assertEquals( $expected, $seen['sync'] );
+ $this->assertNull( $seen['validator']['shirt-s']['vendor'] );
+ $this->assertNull( $seen['sync']['shirt-s']['vendor'] );
+ }
+
+ /**
+ * @testdox Should leave a value that its set_callback refused out of the sent fields.
+ */
+ public function test_a_refused_value_is_not_in_the_sent_fields(): void {
+ $seen = null;
+ $this->register_validator(
+ 'product',
+ 'test-ext',
+ static function ( \WC_Product $product, array $context ) use ( &$seen ) {
+ $seen = $context['fields'][ $product ];
+ return null;
+ }
+ );
+ $this->register_vendor_field( 'product' );
+ $this->reset_registries();
+ $product = \WC_Helper_Product::create_simple_product();
+
+ $response = $this->run_ability_response(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $product->get_id(),
+ 'extensions' => array(
+ 'test-ext' => array(
+ 'color' => 'reject',
+ 'vendor' => 'acme',
+ ),
+ ),
+ )
+ );
+
+ $this->assertSame( 400, $response->get_status() );
+ $this->assertSame( array( 'vendor' => 'acme' ), $seen );
+ }
+
+ /**
+ * @testdox Should give a sync the saved objects of its own resource, and the whole call in the context.
+ */
+ public function test_a_sync_gets_the_saved_objects_of_its_own_resource(): void {
+ $seen = array();
+ foreach ( array( 'product', 'order_item' ) as $resource_name ) {
+ $this->register_sync(
+ $resource_name,
+ 'test-ext',
+ static function ( array $saved, array $context ) use ( &$seen, $resource_name ) {
+ $seen[ $resource_name ] = array(
+ 'saved' => array_map( 'get_class', $saved ),
+ 'objects' => array_map( 'get_class', $context['objects'] ),
+ 'primary' => get_class( $context['primary'] ),
+ 'fields' => array_map( static fn( \WC_Data $item ) => $context['fields'][ $item ], $context['objects'] ),
+ );
+ return null;
+ }
+ );
+ }
+ $this->register_vendor_field( 'order_item' );
+ $this->register_product_with_item_ability();
+ $this->reset_registries();
+ $product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
+
+ $this->run_ability(
+ 'test-ext/product-with-item',
+ array(
+ 'id' => $product->get_id(),
+ 'name' => 'Pencil',
+ 'item_extensions' => array( 'test-ext' => array( 'vendor' => 'acme' ) ),
+ )
+ );
+
+ $whole_call = array(
+ 'objects' => array( 'WC_Product_Simple', 'WC_Order_Item_Product' ),
+ 'primary' => 'WC_Product_Simple',
+ 'fields' => array( array(), array( 'vendor' => 'acme' ) ),
+ );
+ $this->assertSame( array( 'saved' => array( 'WC_Product_Simple' ) ) + $whole_call, $seen['product'] );
+ $this->assertSame( array( 'saved' => array( 'WC_Order_Item_Product' ) ) + $whole_call, $seen['order_item'] );
+ }
+
/**
* @testdox Should give a sync the parent that a variation update saves.
*/
@@ -3630,7 +3768,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen ) {
+ static function ( \WC_Product $product, array $context ) use ( &$seen ) {
if ( $product instanceof \WC_Product_Variation ) {
$seen[ $product->get_sku() ] = array_map( static fn( \WC_Product $item ) => $item->get_meta( '_test_color' ), $context['objects'] );
}
@@ -3771,7 +3909,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static fn( \WC_Product $product, ActionableAbility $ability ) => 'woocommerce/product-delete' === $ability->get_name() && 'keep' === $product->get_sku()
+ static fn( \WC_Product $product, array $context ) => 'woocommerce/product-delete' === $context['ability'] && 'keep' === $product->get_sku()
? new \WP_Error( 'test_keep', 'Keep it.' )
: null
);
@@ -3809,7 +3947,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen ) {
+ static function ( \WC_Product $product, array $context ) use ( &$seen ) {
if ( $product instanceof \WC_Product_Variation ) {
$seen[] = array( $product->get_parent_id(), $context['primary']->get_name(), $context['deleting'] );
}
@@ -3839,7 +3977,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen, $kept ) {
+ static function ( \WC_Product $product, array $context ) use ( &$seen, $kept ) {
$seen[ $product->get_id() ] = $context['deleting'];
return $context['deleting'] && $kept === $product->get_id()
? new \WP_Error( 'test_keep', 'Keep it.' )
@@ -3897,8 +4035,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse ) {
- unset( $ability );
+ static function ( \WC_Product $product, array $context ) use ( &$seen, &$refuse ) {
$seen[ $product->get_id() ] = $context['deleting'];
return $refuse && $context['deleting'] ? new \WP_Error( 'test_keep', 'Keep them.' ) : null;
}
@@ -3906,7 +4043,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
'product',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+ static function ( array $saved, array $context ) use ( &$deleted ) {
unset( $saved, $ability );
$deleted = array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['deleted'] );
return null;
@@ -3945,8 +4082,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'test-ext',
- static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse, $kept ) {
- $seen[ $product->get_id() ] = array( $ability->get_name(), $context['deleting'] );
+ static function ( \WC_Product $product, array $context ) use ( &$seen, &$refuse, $kept ) {
+ $seen[ $product->get_id() ] = array( $context['ability'], $context['deleting'] );
return $refuse && $kept === $product->get_id()
? new \WP_Error( 'test_keep', 'Keep it.' )
: null;
@@ -3986,16 +4123,15 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'order',
'test-ext',
- static function ( \WC_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse ) {
- $seen[] = array( $order->get_id(), $ability->get_name(), $context['deleting'] );
+ static function ( \WC_Order $order, array $context ) use ( &$seen, &$refuse ) {
+ $seen[] = array( $order->get_id(), $context['ability'], $context['deleting'] );
return $refuse ? new \WP_Error( 'test_cancel_first', 'Cancel it first.' ) : null;
}
);
$this->register_sync(
'order',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$synced ) {
- unset( $ability );
+ static function ( array $saved, array $context ) use ( &$synced ) {
$synced[] = array(
count( $saved ),
array_map( static fn( \WC_Order $order ) => $order->get_id(), $context['trashed'] ),
@@ -4062,8 +4198,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'order',
'test-ext',
- static function ( \WC_Abstract_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse, $refund_id ) {
- unset( $ability );
+ static function ( \WC_Abstract_Order $order, array $context ) use ( &$seen, &$refuse, $refund_id ) {
$seen[ $order->get_id() ] = $context['deleting'];
return $refuse && $refund_id === $order->get_id() ? new \WP_Error( 'test_keep_refund', 'Keep the refund.' ) : null;
}
@@ -4071,7 +4206,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
'order',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+ static function ( array $saved, array $context ) use ( &$deleted ) {
unset( $saved, $ability );
$deleted = array_map( static fn( \WC_Abstract_Order $order ) => $order->get_id(), $context['deleted'] );
}
@@ -4123,8 +4258,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'order',
'test-ext',
- static function ( \WC_Abstract_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse, $grandchild_id ) {
- unset( $ability );
+ static function ( \WC_Abstract_Order $order, array $context ) use ( &$seen, &$refuse, $grandchild_id ) {
$seen[ $order->get_id() ] = $context['deleting'];
return $refuse && $grandchild_id === $order->get_id() ? new \WP_Error( 'test_keep_child', 'Keep the refund of the child.' ) : null;
}
@@ -4132,7 +4266,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
'order',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+ static function ( array $saved, array $context ) use ( &$deleted ) {
unset( $saved, $ability );
$deleted = array_map( static fn( \WC_Abstract_Order $order ) => $order->get_id(), $context['deleted'] );
}
@@ -4390,8 +4524,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
$resource_name,
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$synced, $resource_name ) {
- unset( $saved, $ability );
+ static function ( array $saved, array $context ) use ( &$synced, $resource_name ) {
+ unset( $saved );
$synced[] = array( $resource_name, array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['trashed'] ) );
return null;
}
@@ -4508,8 +4642,9 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'input_schema' => array(
'type' => 'object',
'properties' => array(
- 'id' => array( 'type' => 'integer' ),
- 'name' => array( 'type' => 'string' ),
+ 'id' => array( 'type' => 'integer' ),
+ 'name' => array( 'type' => 'string' ),
+ 'item_extensions' => array( 'type' => 'object' ),
),
),
'output_schema' => array( 'type' => 'object' ),
@@ -5258,7 +5393,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_sync(
'product',
'test-ext',
- static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted, &$refuse ) {
+ static function ( array $saved, array $context ) use ( &$deleted, &$refuse ) {
unset( $saved, $ability );
$deleted = array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['deleted'] );
return $refuse ? new \WP_Error( 'test_refused', 'Refused.' ) : null;
@@ -6352,8 +6487,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'order',
'test-ext',
- static function ( \WC_Order $subject, \WP_Ability $current ) use ( &$ability ) {
- $ability = $current->get_name();
+ static function ( \WC_Order $subject, array $context ) use ( &$ability ) {
+ $ability = $context['ability'];
if ( 'yes' === $subject->get_meta( '_test_locked' ) && 'completed' === $subject->get_status() ) {
return new \WP_Error( 'test_locked', 'Use test-ext/order-unlock first.' );
}
@@ -6888,8 +7023,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_validator(
'product',
'other_ext',
- static function ( \WC_Product $subject, \WP_Ability $ability ) {
- return 'test-ext/product-rename' === $ability->get_name()
+ static function ( \WC_Product $subject, array $context ) {
+ return 'test-ext/product-rename' === $context['ability']
? new \WP_Error( 'test_rename_refused', 'Rename refused.' )
: null;
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/TestProductWithItemAbility.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/TestProductWithItemAbility.php
index a1d52a90d21..1971a146096 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/TestProductWithItemAbility.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/TestProductWithItemAbility.php
@@ -19,6 +19,13 @@ class TestProductWithItemAbility extends TestProductRenameAbility {
*/
public static string $item_resource = 'order_item';
+ /**
+ * The order item of the call.
+ *
+ * @var \WC_Order_Item_Product
+ */
+ private \WC_Order_Item_Product $item;
+
/**
* Rename the product in memory, and return a new order item as a secondary object of the `$item_resource` resource.
*
@@ -28,6 +35,18 @@ class TestProductWithItemAbility extends TestProductRenameAbility {
*/
public function change( $subject, array $input ) {
parent::change( $subject, $input );
- return array( array( new \WC_Order_Item_Product(), array(), self::$item_resource ) );
+ $this->item = new \WC_Order_Item_Product();
+ return array( array( $this->item, $input['item_extensions'] ?? array(), self::$item_resource ) );
+ }
+
+ /**
+ * Save the product, then the order item.
+ *
+ * @param \WC_Product $subject Product.
+ * @return null|\WP_Error
+ */
+ protected function save( $subject ) {
+ $this->item->save();
+ return parent::save( $subject );
}
}