Commit f26f37f2792 for woocommerce
commit f26f37f27923f351560033e33be59937702b3434
Author: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com>
Date: Fri Dec 4 17:03:44 2026 -0300
Keep the data of prime callbacks in Core (#71384)
* Keep the data of prime callbacks in Core and pass it to get_callbacks
A prime callback now returns its data keyed by object ID. Core keeps each
entry for the object instance of the list, gives an empty array to the
objects the callback left out, and passes the entry to the get_callbacks
of the same namespace. A get_callback gets null when no list was loaded
for its object or the prime callback failed, and then loads its own data.
Core forgets an entry once its object is read, so a later write never
gets it. A second prime callback for the same resource and namespace is
refused.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Say that the second parameter of a get_callback always receives the entry
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Drop the prime entries when a write starts
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Say that a built-in function must be wrapped to be a get_callback
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Read the ID of a primed object from its resource
prime() keyed the entries by get_id() or a term, comment or post ID property, so objects with another ID field, such as a shipping method, got no entry. It now reads the ID with the object_id_callback of the resource, which register_prime() requires to be registered.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Return an array from the prime callback of the attribute terms test
A prime callback that returns no array is now reported with a notice.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Say when a prime callback is not needed and what a nested list does to the entries
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-1762-keep-the-data-of-prime-callbacks-in-core b/plugins/woocommerce/changelog/wooai-1762-keep-the-data-of-prime-callbacks-in-core
new file mode 100644
index 00000000000..1d375a15c9e
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1762-keep-the-data-of-prime-callbacks-in-core
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Keep the data of extensible ability prime callbacks in Core; experimental feature, off by default.
+
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index 704bc249eec..c89a5c6e0e2 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -231,7 +231,8 @@ abstract class ActionableAbility extends Ability {
return $this->unknown_resource_error( $this->get_resource(), 'get_resource' );
}
- $input = is_array( $input ) ? $input : array();
+ $input = is_array( $input ) ? $input : array();
+ ExtensibleAbilities::forget_primed();
$subject = $this->load( $input );
if ( is_wp_error( $subject ) ) {
return $subject;
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index cbdff24a5db..ee11b7de41a 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -77,6 +77,14 @@ class ExtensibleAbilities {
*/
private static array $order_emails = array();
+ /**
+ * Entries that the prime callbacks returned for the last list of each resource,
+ * keyed by resource, then object instance, then namespace.
+ *
+ * @var array<string, \SplObjectStorage<object, array<string, mixed>>>
+ */
+ private static array $primed = array();
+
/**
* Whether the store enabled the experimental feature.
*
@@ -203,7 +211,15 @@ class ExtensibleAbilities {
* 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
+ * @type callable $get_callback Optional. Receives the object and the entry that the prime callback of the
+ * same namespace returned for it, and returns the value. The entry is null
+ * when no list was loaded for the object, or when the prime callback failed
+ * or returned no array. The callback then loads the data of that one
+ * object itself. A user-defined function, method or closure that needs no
+ * entry can take only the object. A PHP built-in function with a fixed
+ * number of parameters, such as `get_class`, fails on the extra argument,
+ * so wrap it in a closure. A second parameter always receives the entry, so the callback must not
+ * use it for another value with a default. 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
* value that `output_schema` does not allow fails the call with
@@ -795,10 +811,13 @@ class ExtensibleAbilities {
* Register a prime callback on a resource. Before an ability formats a list
* of objects of the resource, Core calls every prime callback of the
* resource once, with the full list. An extension loads the data of its
- * fields for the whole list in one query, keeps it in its own cache, and
- * its get_callback reads from there.
+ * fields for the whole list in one query and returns it. Core passes the
+ * entry of each object to the get_callbacks of the same namespace. Data in
+ * the meta of a product or an order needs no prime callback: WooCommerce
+ * loads that meta with the object, and clears it when the object is saved.
*
- * Call it inside the `woocommerce_extensible_abilities_init` action. Prime
+ * Call it inside the `woocommerce_extensible_abilities_init` action. A namespace
+ * has one prime callback per resource, and a second one is refused. Prime
* callbacks run only when the `extensible_abilities` feature is on, in the
* order they were registered.
*
@@ -809,31 +828,43 @@ class ExtensibleAbilities {
*
* @type string $resource Resource that an ability formats, such as `product`.
* @type string $namespace Slug of the extension that owns the callback, such as `google`.
- * @type callable $callback Receives `object[] $objects`, every object the ability formats. The
- * callback skips the objects it does not need. Core ignores the
- * return value. When it throws, Core logs the error and formats
- * the objects anyway, so the get_callback must still load its
- * data for an object that is not in the cache. Core calls prime
- * callbacks only on reads, not on writes. Key the cache by object ID,
- * and remove the entry of an object when the object is saved, for
- * example on `woocommerce_update_product`. Otherwise a write after a
- * read in the same request returns the old value. Empty the cache at the start of
- * every call, so a failed load leaves no old entries.
+ * @type callable $callback Receives `object[] $objects`, every object the ability formats, and
+ * returns an array keyed by object ID, with only the objects that have
+ * data. Each object of the list gets its entry, and an object the array
+ * leaves out gets an empty array. Data that the whole list shares goes
+ * in the entry of each object. Core reads the ID with the
+ * `object_id_callback` of the resource. When the callback
+ * throws, Core logs the error, and the get_callbacks get null. They
+ * also get null when it returns no array, which Core reports with
+ * wc_doing_it_wrong(). Core keeps an entry until the get_callbacks of
+ * its object have read it, until the next list of the resource, or
+ * until an ActionableAbility starts a write, so such a write never
+ * gets an old entry. Core calls prime callbacks only on reads, not on
+ * writes.
* }
*/
public static function register_prime( array $args ): void {
if ( ! self::check_callback_args( $args, __METHOD__, 'prime callback', '11.4.0' ) ) {
return;
}
+ if ( in_array( $args['namespace'], array_column( self::$primes[ $args['resource'] ] ?? array(), 'namespace' ), true ) ) {
+ wc_doing_it_wrong( __METHOD__, sprintf( 'The "%1$s" namespace already has a prime callback for "%2$s". Load the data of all its fields in that one callback.', $args['namespace'], $args['resource'] ), '11.5.0' );
+ return;
+ }
self::$primes[ $args['resource'] ][] = $args;
}
/**
* Call every prime callback of a resource with the objects that an ability
- * is about to format. A callback that throws is logged, and the next one runs.
- * An extension that registers its own resource calls it from its list
- * abilities before add_fields_to_object(), as Core's abilities do.
+ * is about to format, and keep the entries they return for add_fields_to_object().
+ * The entries replace those of the last list of the resource, also when a
+ * get_callback lists the same resource while the first list is formatted. The
+ * objects of the first list that are not formatted yet then get null, and each
+ * get_callback loads the data of its object itself. A callback that
+ * throws is logged, and the next one runs. An extension that registers its own
+ * resource calls it from its list abilities before add_fields_to_object(), as
+ * Core's abilities do.
*
* @since 11.4.0
*
@@ -841,18 +872,47 @@ class ExtensibleAbilities {
* @param object[] $objects Objects to format.
*/
public static function prime( string $resource_name, array $objects ): void {
+ unset( self::$primed[ $resource_name ] );
if ( empty( self::$primes[ $resource_name ] ) || empty( $objects ) || ! self::is_enabled() ) {
return;
}
$objects = array_values( $objects );
+ $primed = new \SplObjectStorage();
foreach ( self::$primes[ $resource_name ] as $args ) {
try {
- call_user_func( $args['callback'], $objects );
+ $data = call_user_func( $args['callback'], $objects );
} catch ( \Throwable $e ) {
self::log_error( sprintf( 'Ability prime callback of "%s" for "%s" failed: %s', $args['namespace'], $resource_name, $e->getMessage() ) );
+ continue;
+ }
+ if ( ! is_array( $data ) ) {
+ wc_doing_it_wrong( __CLASS__ . '::register_prime', sprintf( 'The prime callback of "%1$s" for "%2$s" must return an array keyed by object ID. Return an empty array when no object has data.', $args['namespace'], $resource_name ), '11.5.0' );
+ continue;
+ }
+ foreach ( $objects as $subject ) {
+ $id = self::get_object_id( $subject, $resource_name );
+ if ( 0 === $id ) {
+ continue;
+ }
+ $entries = $primed->contains( $subject ) ? $primed[ $subject ] : array();
+ $entries[ $args['namespace'] ] = $data[ $id ] ?? array();
+ $primed[ $subject ] = $entries;
}
}
+ self::$primed[ $resource_name ] = $primed;
+ }
+
+ /**
+ * Drop the entries of every resource. ActionableAbility calls it when a write starts,
+ * so the write does not format an object with an entry from before the write.
+ *
+ * @internal
+ *
+ * @since 11.5.0
+ */
+ public static function forget_primed(): void {
+ self::$primed = array();
}
/**
@@ -1004,13 +1064,19 @@ class ExtensibleAbilities {
}
$extensions = array();
+ $primed = self::$primed[ $resource_name ] ?? null;
+ $entries = array();
+ if ( null !== $primed && $primed->contains( $subject ) ) {
+ $entries = $primed[ $subject ];
+ $primed->detach( $subject );
+ }
foreach ( self::$fields[ $resource_name ] as $namespace => $fields ) {
foreach ( $fields as $field => $args ) {
if ( ! isset( $args['get_callback'] ) || ! self::field_applies_to( $args, $subject ) ) {
continue;
}
try {
- $value = call_user_func( $args['get_callback'], $subject );
+ $value = call_user_func( $args['get_callback'], $subject, $entries[ $namespace ] ?? null );
} catch ( \Throwable $e ) {
return self::field_callback_failed_error( $args, $e );
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributesQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributesQueryTest.php
index 632903bcf34..f27757414e2 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributesQueryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductAttributesQueryTest.php
@@ -210,6 +210,7 @@ class ProductAttributesQueryTest extends WC_Unit_Test_Case {
'namespace' => 'test-ext',
'callback' => static function ( array $terms ) use ( &$primed ) {
$primed[] = count( $terms );
+ return array();
},
)
);
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index e221a598730..b34ce428bca 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -1150,7 +1150,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
}
/**
- * @testdox Should call the $resource_name prime callbacks of each extension once with the full list, in registration order.
+ * @testdox Should call the $resource_name prime callbacks once with the full list, and pass each object its own entry.
* @dataProvider provide_list_abilities
*
* @param string $resource_name Resource the ability lists.
@@ -1160,18 +1160,17 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
*/
public function test_prime_callbacks_get_the_full_list_once( string $resource_name, string $ability, string $list_key, callable $create_input ): void {
$calls = array();
- $cache = array();
$this->add_test_action(
'woocommerce_extensible_abilities_init',
- static function () use ( $resource_name, &$cache ) {
+ static function () use ( $resource_name ) {
ExtensibleAbilities::register_field(
array(
'resource' => $resource_name,
'namespace' => 'test-ext',
'field' => 'primed',
'output_schema' => array( 'type' => 'string' ),
- 'get_callback' => static function ( $data_object ) use ( &$cache ) {
- return $cache[ self::prime_object_id( $data_object ) ] ?? null;
+ 'get_callback' => static function ( $data_object, $entry ) {
+ return is_array( $entry ) ? 'no data' : $entry;
},
)
);
@@ -1181,12 +1180,10 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->register_prime(
$resource_name,
$extension_namespace,
- static function ( array $objects ) use ( &$calls, &$cache, $extension_namespace ) {
+ static function ( array $objects ) use ( &$calls, $extension_namespace ) {
$ids = array_map( array( self::class, 'prime_object_id' ), array_values( $objects ) );
$calls[] = array( $extension_namespace, $ids );
- if ( 'test-ext' === $extension_namespace ) {
- $cache = array_combine( $ids, array_map( static fn( int $id ) => 'primed-' . $id, $ids ) );
- }
+ return array( $ids[0] => $extension_namespace . '-' . $ids[0] );
}
);
}
@@ -1198,9 +1195,8 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$ids = array_column( $list, $id_key );
$this->assertCount( 2, $ids );
$this->assertSame( array( array( 'test-ext', $ids ), array( 'other_ext', $ids ) ), $calls );
- foreach ( $list as $listed ) {
- $this->assertSame( 'primed-' . $listed[ $id_key ], $listed['extensions']['test-ext']['primed'] );
- }
+ $this->assertSame( 'test-ext-' . $ids[0], $list[0]['extensions']['test-ext']['primed'] );
+ $this->assertSame( 'no data', $list[1]['extensions']['test-ext']['primed'], 'An object the prime callback leaves out gets an empty array.' );
}
/**
@@ -1395,6 +1391,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'test-ext',
static function ( array $objects ) use ( &$calls, $resource_name ) {
$calls[ $resource_name ][] = array_map( static fn( $data_object ) => $data_object->get_id(), $objects );
+ return array();
}
);
}
@@ -1418,7 +1415,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
}
/**
- * @testdox Should log a prime callback that throws, run the next one, and still return the fields.
+ * @testdox Should log a prime callback that throws, run the next one, and pass null to its get_callbacks.
*/
public function test_a_prime_callback_that_throws_is_logged(): void {
$product = \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
@@ -1443,13 +1440,126 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'other_ext',
static function () use ( &$calls ) {
++$calls;
+ return array();
}
);
+ $this->register_entry_field();
+
$products = $this->run_ability( 'woocommerce/products-query', array( 'search' => 'Pen' ) )['products'];
$this->assertSame( 1, $calls );
- $this->assertSame( array( 'code' => 'A1' ), $products[0]['extensions']['test-ext'] );
+ $this->assertSame(
+ array(
+ 'code' => 'A1',
+ 'entry' => 'loaded',
+ ),
+ $products[0]['extensions']['test-ext']
+ );
+ }
+
+ /**
+ * @testdox Should report a prime callback that returns no array, and pass null to its get_callbacks.
+ */
+ public function test_a_prime_callback_that_returns_no_array_is_reported(): void {
+ $this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_prime' );
+ \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
+ $this->register_prime( 'product', 'test-ext', static fn() => 'loaded' );
+ $this->register_entry_field();
+
+ $products = $this->run_ability( 'woocommerce/products-query', array( 'search' => 'Pen' ) )['products'];
+
+ $this->assertSame( 'loaded', $products[0]['extensions']['test-ext']['entry'] );
+ }
+
+ /**
+ * @testdox Should pass a primed entry to one read of its object, and drop the unread entries when a write starts.
+ */
+ public function test_a_primed_entry_is_read_once(): void {
+ $product = \WC_Helper_Product::create_simple_product();
+ $this->register_prime( 'product', 'test-ext', static fn( array $objects ) => array( $objects[0]->get_id() => 'primed' ) );
+ $this->register_entry_field();
+ $this->get_output_schema( 'woocommerce/products-query' );
+
+ ExtensibleAbilities::prime( 'product', array( $product ) );
+ $read = ExtensibleAbilities::add_fields_to_object( array(), 'product', $product );
+ $re_read = ExtensibleAbilities::add_fields_to_object( array(), 'product', $product );
+
+ $this->assertSame( 'primed', $read['extensions']['test-ext']['entry'] );
+ $this->assertSame( 'loaded', $re_read['extensions']['test-ext']['entry'], 'A write that formats the same object must not get the old entry.' );
+
+ ExtensibleAbilities::prime( 'product', array( $product ) );
+ $this->run_ability(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $product->get_id(),
+ 'name' => 'Renamed',
+ )
+ );
+ $after_write = ExtensibleAbilities::add_fields_to_object( array(), 'product', $product );
+
+ $this->assertSame( 'loaded', $after_write['extensions']['test-ext']['entry'], 'A write drops the entry of an object that no read formatted.' );
+ }
+
+ /**
+ * @testdox Should key prime entries by the ID that the resource reads, for objects without get_id().
+ */
+ public function test_a_prime_entry_uses_the_id_of_the_resource(): void {
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_resources_init',
+ static function () {
+ ExtensibleAbilities::register_resource( 'ticket', self::get_ticket_resource_args() );
+ }
+ );
+ $this->enable_extensible_abilities(
+ static function () {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => 'ticket',
+ 'namespace' => 'test-ext',
+ 'field' => 'entry',
+ 'output_schema' => array( 'type' => 'string' ),
+ 'get_callback' => static fn( $ticket, $entry ) => $entry ?? 'loaded',
+ )
+ );
+ ExtensibleAbilities::register_prime(
+ array(
+ 'resource' => 'ticket',
+ 'namespace' => 'test-ext',
+ 'callback' => static fn( array $tickets ) => array( $tickets[0]->id => 'primed' ),
+ )
+ );
+ }
+ );
+ $ticket = (object) array( 'id' => 7 );
+
+ ExtensibleAbilities::prime( 'ticket', array( $ticket ) );
+ $read = ExtensibleAbilities::add_fields_to_object( array(), 'ticket', $ticket );
+
+ $this->assertSame( 'primed', $read['extensions']['test-ext']['entry'] );
+ }
+
+ /**
+ * @testdox Should refuse a second prime callback for the same resource and namespace.
+ */
+ public function test_a_second_prime_callback_of_a_namespace_is_refused(): void {
+ $this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_prime' );
+ \WC_Helper_Product::create_simple_product( true, array( 'name' => 'Pen' ) );
+ $calls = array();
+ foreach ( array( 'first', 'second' ) as $name ) {
+ $this->register_prime(
+ 'product',
+ 'test-ext',
+ static function () use ( &$calls, $name ) {
+ $calls[] = $name;
+ return array();
+ }
+ );
+ }
+
+ $this->run_ability( 'woocommerce/products-query', array( 'search' => 'Pen' ) );
+
+ $this->assertSame( array( 'first' ), $calls );
}
/**
@@ -1475,6 +1585,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'other_ext',
static function () use ( &$calls ) {
++$calls;
+ return array();
}
);
@@ -1495,6 +1606,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
'test-ext',
static function () use ( &$calls ) {
++$calls;
+ return array();
}
);
$this->get_output_schema( 'woocommerce/products-query' );
@@ -7808,6 +7920,26 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
);
}
+ /**
+ * Register the test-ext.entry product field, which returns its prime entry, or `loaded` when it gets null.
+ */
+ private function register_entry_field(): void {
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_init',
+ static function () {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => 'product',
+ 'namespace' => 'test-ext',
+ 'field' => 'entry',
+ 'output_schema' => array( 'type' => 'string' ),
+ 'get_callback' => static fn( \WC_Product $product, $entry ) => $entry ?? 'loaded',
+ )
+ );
+ }
+ );
+ }
+
/**
* Register test-ext/order-status, an ActionableAbility of an extension that changes orders.
*
@@ -7948,7 +8080,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
private function reset_registries(): void {
global $wp_actions;
- foreach ( array( 'fields', 'validators', 'syncs', 'primes', 'filters', 'order_emails' ) as $property ) {
+ foreach ( array( 'fields', 'validators', 'syncs', 'primes', 'primed', 'filters', 'order_emails' ) as $property ) {
$reflection = new \ReflectionProperty( ExtensibleAbilities::class, $property );
$reflection->setAccessible( true );
$reflection->setValue( null, array() );