Products: Avoid fatal during variation search (#45776)

* Products: Avoid fatal during variation search

Most product types' data objects store `WC_Product_Attribute` objects in
their attributes property, whereas Product variation data objects store
an associative array of key/value pairs in their attributes property.
This is problematic because it means a fatal error can be thrown when
code assumes that a product's attributes are objects with methods rather
than simply strings. Ideally, attributes would work the same everywhere,
but it would be challenging to fix that in the codebase without breaking
backcompat. So instead, in this PR, we are simply adding some logic in
the `find_matching_product_variation` method to ensure that we're not
trying to retrieve a variation of a product object that is already a
variation.

* Fix linting issue
This commit is contained in:
Corey McKrill 2024-03-21 10:07:09 -07:00 committed by GitHub
parent 5ee4a4c1b1
commit b2d70262b7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 19 additions and 0 deletions

View File

@ -0,0 +1,4 @@
Significance: patch
Type: fix
Avoid trying to find a product variation of a product variation

View File

@ -1099,6 +1099,11 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da
* @return int Matching variation ID or 0.
*/
public function find_matching_product_variation( $product, $match_attributes = array() ) {
if ( 'variation' === $product->get_type() ) {
// Can't get a variation of a variation.
return 0;
}
global $wpdb;
$meta_attribute_names = array();

View File

@ -1082,5 +1082,15 @@ class WC_Tests_Product_Data_Store extends WC_Unit_Test_Case {
);
$this->assertEquals( $children[2], $match );
// Test trying to get a variation of a variation.
$variation = wc_get_product( $children[0] );
$match = $data_store->find_matching_product_variation(
$variation,
array(
'attribute_pa_size' => 'small',
)
);
$this->assertEquals( 0, $match );
}
}