Implement new featured field check

Internal logic:

- If the featured field is absent from all image objects in the request, set the first image in the array to featured.
- If the featured field is present in all image objects, we respect the value and set the featured image accordingly.
- If the featured field is absent from some image object, we set the featured image based on whether a true value exists; otherwise, we set the first image as featured.
- if multiple images have the featured field set to true, return a new 400 bad request response..
This commit is contained in:
Csaba Maulis 2023-04-20 13:16:21 +08:00
parent 135d6f2b27
commit 46dceffece
No known key found for this signature in database
GPG Key ID: 078894AC01BC6E63
2 changed files with 27 additions and 4 deletions

View File

@ -308,6 +308,31 @@ class WC_REST_Products_Controller extends WC_REST_Products_V2_Controller {
$images = is_array( $images ) ? array_filter( $images ) : array();
if ( ! empty( $images ) ) {
$featured_image_index = 0;
$featured_image_count = 0;
// Collect featured field usage.
foreach ( $images as $index => $image ) {
if ( isset( $image['featured'] ) && $image['featured'] ) {
$featured_image_index = $index;
$featured_image_count++;
}
}
// Handle multiple featured images.
if ($featured_image_count > 1) {
throw new WC_REST_Exception(
'woocommerce_rest_product_featured_image_count',
__( 'Only one featured image is allowed.', 'woocommerce' ),
400
);
}
// If no featured image is set, and the first image explicitly set to false do not set featured at all.
if ( 0 === $featured_image_count && isset( $images[0]['featured'] ) && false === $images[0]['featured'] ) {
$featured_image_index = null;
}
$gallery = array();
foreach ( $images as $index => $image ) {
@ -332,9 +357,7 @@ class WC_REST_Products_Controller extends WC_REST_Products_V2_Controller {
throw new WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
}
$featured_image = $product->get_image_id();
if ( 0 === $index ) {
if ( $featured_image_index === $index ) {
$product->set_image_id( $attachment_id );
} else {
$gallery[] = $attachment_id;

View File

@ -263,7 +263,7 @@ class WC_REST_Products_Controller_Tests extends WC_REST_Unit_Test_Case {
$this->assertNotWPError( $gallery_url );
$gallery_id = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $gallery_url ) );
$featured_url = media_sideload_image( 'http://cldup.com/Dr1Bczxq4q.png', $product->get_id(), 'featured', 'src' );
$featured_url = media_sideload_image( 'https://cldup.com/Dr1Bczxq4q.png', $product->get_id(), 'featured', 'src' );
$this->assertNotWPError( $featured_url );
$featured_id = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE guid = %s", $featured_url ) );