Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 7c69cef

Browse files
committed
Ensure the Product endpoint relies on the fetch_dummy_products_to_update method for fetching dummy products to avoid code repetition and add safety checks and handle errors in case certain properties are not available.
1 parent 827bc3c commit 7c69cef

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

src/StoreApi/Routes/V1/AI/Product.php

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -70,36 +70,37 @@ public function get_args() {
7070
*/
7171
protected function get_route_post_response( \WP_REST_Request $request ) {
7272
$product_updater = new ProductUpdater();
73-
74-
$dummy_products = $product_updater->fetch_product_ids( 'dummy' );
75-
76-
if ( ! is_array( $dummy_products ) ) {
77-
$error = new \WP_Error( 'failed_to_fetch_dummy_products', __( 'Failed to fetch dummy products.', 'woo-gutenberg-products-block' ) );
78-
return $this->error_to_response( $error );
73+
$dummy_products = $product_updater->fetch_dummy_products_to_update();
74+
75+
if ( empty( $dummy_products ) ) {
76+
return rest_ensure_response(
77+
array(
78+
'ai_content_generated' => true,
79+
)
80+
);
7981
}
8082

81-
// Identify dummy products that need to have their content updated.
82-
$dummy_products_ids = $product_updater->fetch_product_ids( 'dummy' );
83-
84-
if ( ! is_array( $dummy_products_ids ) ) {
85-
$error = new \WP_Error( 'failed_to_fetch_dummy_products', __( 'Failed to fetch dummy products.', 'woo-gutenberg-products-block' ) );
86-
return $this->error_to_response( $error );
83+
$index = $request['index'];
84+
if ( ! is_numeric( $index ) ) {
85+
return rest_ensure_response(
86+
array(
87+
'ai_content_generated' => false,
88+
)
89+
);
8790
}
8891

89-
$dummy_products = array_map(
90-
function ( $product ) {
91-
return wc_get_product( $product->ID );
92-
},
93-
$dummy_products_ids
94-
);
95-
96-
$index = $request['index'];
97-
$products_information = $request['products_information'];
92+
$products_information = $request['products_information'] ?? array();
9893

99-
if ( $product_updater->should_update_dummy_product( $dummy_products[ $index ] ) ) {
100-
$product_updater->update_product_content( $dummy_products[ $index ], $products_information );
94+
if ( ! isset( $dummy_products[ $index ] ) ) {
95+
return rest_ensure_response(
96+
array(
97+
'ai_content_generated' => false,
98+
)
99+
);
101100
}
102101

102+
$product_updater->update_product_content( $dummy_products[ $index ], $products_information );
103+
103104
return rest_ensure_response(
104105
array(
105106
'ai_content_generated' => true,

0 commit comments

Comments
 (0)