Fix `Error: Failed opening required '.../wp-content/plugins/woocommerce/src/StoreApi/Schemas/V1/AI/ProductsSchema.php` fatal error (WC 9.4) (#52023)

* Revert "CYS - Move the `private/patterns` endpoint to woocommerce admin API (#50400)"

This reverts commit 091141218e.

* Revert "CYS - Move the `ai/products` endpoint to woocommerce admin API (#50396)"

This reverts commit ae6f7837b2.

* fix endpoint

* Add changefile(s) from automation for the following project(s): woocommerce

* fix e2e test

* add declare strict type declaration

* Remove old TODO comment

* Add strict_types to Products route class file

---------

Co-authored-by: Luigi Teschio <gigitux@gmail.com>
Co-authored-by: github-actions <github-actions@github.com>
This commit is contained in:
Albert Juhé Lluveras 2024-10-15 12:39:15 +02:00 committed by GitHub
parent 08e624f7da
commit 6a36962383
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 381 additions and 352 deletions

View File

@ -49,7 +49,7 @@ export const OptInSubscribe = () => {
await apiFetch< {
success: boolean;
} >( {
path: '/wc-admin/patterns',
path: '/wc/private/patterns',
method: 'POST',
} );
};

View File

@ -264,7 +264,7 @@ export const SidebarNavigationScreenHomepagePTK = ( {
<Button
onClick={ async () => {
await apiFetch( {
path: `/wc-admin/patterns`,
path: `/wc/private/patterns`,
method: 'POST',
} );

View File

@ -220,7 +220,7 @@ const resetPatternsAndProducts = () => async () => {
method: 'DELETE',
} ),
apiFetch( {
path: '/wc-admin/ai/products',
path: '/wc/private/ai/products',
method: 'DELETE',
} ),
] );
@ -278,7 +278,7 @@ export const updateStorePatterns = async (
additional_errors?: unknown[];
} >( [
apiFetch( {
path: '/wc-admin/ai/products',
path: '/wc/private/ai/products',
method: 'POST',
data: {
business_description:

View File

@ -168,7 +168,7 @@ export const installPatterns = async () => {
const { success } = await apiFetch< {
success: boolean;
} >( {
path: '/wc-admin/patterns',
path: '/wc/private/patterns',
method: 'POST',
} );

View File

@ -106,7 +106,7 @@ const fetchIsFontLibraryAvailable = async () => {
const fetchIsPTKPatternsAPIAvailable = async () => {
try {
await apiFetch( {
path: '/wc-admin/patterns',
path: '/wc/private/patterns',
method: 'GET',
} );

View File

@ -0,0 +1,4 @@
Significance: patch
Type: fix
Fix `Error: Failed opening required '.../wp-content/plugins/woocommerce/src/StoreApi/Schemas/V1/AI/ProductsSchema.php` fatal error

View File

@ -1,128 +0,0 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API\AI;
use Automattic\WooCommerce\Blocks\AI\Connection;
use Automattic\WooCommerce\Blocks\AIContent\UpdateProducts;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
defined( 'ABSPATH' ) || exit;
/**
* Product controller
*
* @internal
*/
class Products extends AIEndpoint {
/**
* Endpoint.
*
* @var string
*/
protected $endpoint = 'products';
/**
* Register routes.
*/
public function register_routes() {
$this->register(
array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'generate_products_content' ),
'permission_callback' => array( Middleware::class, 'is_authorized' ),
'args' => array(
'business_description' => array(
'description' => __( 'The business description for a given store.', 'woocommerce' ),
'type' => 'string',
),
'images' => array(
'description' => __( 'The images for a given store.', 'woocommerce' ),
'type' => 'object',
),
),
),
array(
'methods' => \WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_products' ),
'permission_callback' => array( Middleware::class, 'is_authorized' ),
),
)
);
}
/**
* Generate the content for the products.
*
* @param WP_REST_Request $request Request object.
*
* @return WP_Error|WP_REST_Response
*/
public function generate_products_content( WP_REST_Request $request ) {
$allow_ai_connection = get_option( 'woocommerce_blocks_allow_ai_connection' );
if ( ! $allow_ai_connection ) {
return rest_ensure_response(
new WP_Error(
'ai_connection_not_allowed',
__( 'AI content generation is not allowed on this store. Update your store settings if you wish to enable this feature.', 'woocommerce' )
)
);
}
$business_description = sanitize_text_field( wp_unslash( $request['business_description'] ) );
if ( empty( $business_description ) ) {
$business_description = get_option( 'woo_ai_describe_store_description' );
}
$ai_connection = new Connection();
$site_id = $ai_connection->get_site_id();
if ( is_wp_error( $site_id ) ) {
return $site_id;
}
$token = $ai_connection->get_jwt_token( $site_id );
if ( is_wp_error( $token ) ) {
return $token;
}
$images = $request['images'];
$populate_products = ( new UpdateProducts() )->generate_content( $ai_connection, $token, $images, $business_description );
if ( is_wp_error( $populate_products ) ) {
return $populate_products;
}
if ( ! isset( $populate_products['product_content'] ) ) {
return new WP_Error( 'product_content_not_found', __( 'Product content not found.', 'woocommerce' ) );
}
$product_content = $populate_products['product_content'];
$item = array(
'ai_content_generated' => true,
'product_content' => $product_content,
);
return rest_ensure_response( $item );
}
/**
* Remove products generated by AI.
*
* @return WP_Error|WP_REST_Response
*/
public function delete_products() {
( new UpdateProducts() )->reset_products_content();
return rest_ensure_response( array( 'removed' => true ) );
}
}

View File

@ -92,8 +92,6 @@ class Init {
'Automattic\WooCommerce\Admin\API\AI\Images',
'Automattic\WooCommerce\Admin\API\AI\Patterns',
'Automattic\WooCommerce\Admin\API\AI\Product',
'Automattic\WooCommerce\Admin\API\AI\Products',
'Automattic\WooCommerce\Admin\API\Patterns',
);
}

View File

@ -1,93 +0,0 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API;
use Automattic\WooCommerce\Blocks\BlockPatterns;
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Patterns\PTKClient;
use Automattic\WooCommerce\Blocks\Patterns\PTKPatternsStore;
use WP_Error;
use WP_REST_Response;
defined( 'ABSPATH' ) || exit;
/**
* Patterns controller
*
* @internal
*/
class Patterns {
/**
* Register routes.
*/
public function register_routes() {
register_rest_route(
'wc-admin',
'/patterns',
array(
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( $this, 'get_pattern' ),
'permission_callback' => function () {
return is_user_logged_in();
},
),
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'update_patterns' ),
'permission_callback' => function () {
return is_user_logged_in();
},
),
)
);
}
/**
* Fetch a single pattern from the PTK to ensure the API is available.
*
* @return WP_Error|WP_REST_Response
*/
public function get_pattern() {
$ptk_client = Package::container()->get( PTKClient::class );
$response = $ptk_client->fetch_patterns(
array(
'per_page' => 1,
)
);
if ( is_wp_error( $response ) ) {
return $response;
}
return rest_ensure_response(
array(
'success' => true,
)
);
}
/**
* Fetch the patterns from the PTK and update the transient.
*
* @return WP_REST_Response
*/
public function update_patterns() {
$ptk_patterns_store = Package::container()->get( PTKPatternsStore::class );
$ptk_patterns_store->fetch_patterns();
$block_patterns = Package::container()->get( BlockPatterns::class );
$block_patterns->register_ptk_patterns();
return rest_ensure_response(
array(
'success' => true,
)
);
}
}

View File

@ -5,6 +5,8 @@
* Handles requests to /products/*
*/
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Admin\API;
defined( 'ABSPATH' ) || exit;

View File

@ -0,0 +1,51 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Routes\V1\AI;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
/**
* Middleware class.
*
* @internal
*/
class Middleware {
/**
* Ensure that the user is allowed to make this request.
*
* @throws RouteException If the user is not allowed to make this request.
* @return boolean
*/
public static function is_authorized() {
try {
if ( ! current_user_can( 'manage_options' ) ) {
throw new RouteException( 'woocommerce_rest_invalid_user', __( 'You are not allowed to make this request. Please make sure you are logged in.', 'woocommerce' ), 403 );
}
} catch ( RouteException $error ) {
return new \WP_Error(
$error->getErrorCode(),
$error->getMessage(),
array( 'status' => $error->getCode() )
);
}
$allow_ai_connection = get_option( 'woocommerce_blocks_allow_ai_connection' );
if ( ! $allow_ai_connection ) {
try {
throw new RouteException( 'ai_connection_not_allowed', __( 'AI content generation is not allowed on this store. Update your store settings if you wish to enable this feature.', 'woocommerce' ), 403 );
} catch ( RouteException $error ) {
return new \WP_Error(
$error->getErrorCode(),
$error->getMessage(),
array( 'status' => $error->getCode() )
);
}
}
return true;
}
}

View File

@ -0,0 +1,154 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Routes\V1\AI;
use Automattic\WooCommerce\Blocks\AI\Connection;
use Automattic\WooCommerce\Blocks\AIContent\UpdateProducts;
use Automattic\WooCommerce\StoreApi\Routes\V1\AbstractRoute;
/**
* Products class.
*
* @internal
*/
class Products extends AbstractRoute {
/**
* The route identifier.
*
* @var string
*/
const IDENTIFIER = 'ai/products';
/**
* The schema item identifier.
*
* @var string
*/
const SCHEMA_TYPE = 'ai/products';
/**
* Get the path of this REST route.
*
* @return string
*/
public function get_path() {
return self::get_path_regex();
}
/**
* Get the path of this rest route.
*
* @return string
*/
public static function get_path_regex() {
return '/ai/products';
}
/**
* Get method arguments for this REST route.
*
* @return array An array of endpoints.
*/
public function get_args() {
return [
[
'methods' => \WP_REST_Server::CREATABLE,
'callback' => [ $this, 'get_response' ],
'permission_callback' => [ Middleware::class, 'is_authorized' ],
'args' => [
'business_description' => [
'description' => __( 'The business description for a given store.', 'woocommerce' ),
'type' => 'string',
],
'images' => [
'description' => __( 'The images for a given store.', 'woocommerce' ),
'type' => 'object',
],
],
],
[
'methods' => \WP_REST_Server::DELETABLE,
'callback' => [ $this, 'get_response' ],
'permission_callback' => [ Middleware::class, 'is_authorized' ],
],
'schema' => [ $this->schema, 'get_public_item_schema' ],
'allow_batch' => [ 'v1' => true ],
];
}
/**
* Generate the content for the products.
*
* @param \WP_REST_Request $request Request object.
*
* @return bool|string|\WP_Error|\WP_REST_Response
*/
protected function get_route_post_response( \WP_REST_Request $request ) {
$allow_ai_connection = get_option( 'woocommerce_blocks_allow_ai_connection' );
if ( ! $allow_ai_connection ) {
return rest_ensure_response(
$this->error_to_response(
new \WP_Error(
'ai_connection_not_allowed',
__( 'AI content generation is not allowed on this store. Update your store settings if you wish to enable this feature.', 'woocommerce' )
)
)
);
}
$business_description = sanitize_text_field( wp_unslash( $request['business_description'] ) );
if ( empty( $business_description ) ) {
$business_description = get_option( 'woo_ai_describe_store_description' );
}
$ai_connection = new Connection();
$site_id = $ai_connection->get_site_id();
if ( is_wp_error( $site_id ) ) {
return $this->error_to_response( $site_id );
}
$token = $ai_connection->get_jwt_token( $site_id );
if ( is_wp_error( $token ) ) {
return $this->error_to_response( $token );
}
$images = $request['images'];
$populate_products = ( new UpdateProducts() )->generate_content( $ai_connection, $token, $images, $business_description );
if ( is_wp_error( $populate_products ) ) {
return $this->error_to_response( $populate_products );
}
if ( ! isset( $populate_products['product_content'] ) ) {
return $this->error_to_response( new \WP_Error( 'product_content_not_found', __( 'Product content not found.', 'woocommerce' ) ) );
}
$product_content = $populate_products['product_content'];
$item = array(
'ai_content_generated' => true,
'product_content' => $product_content,
);
return rest_ensure_response( $item );
}
/**
* Remove products generated by AI.
*
* @param \WP_REST_Request $request Request object.
*
* @return bool|string|\WP_Error|\WP_REST_Response
*/
protected function get_route_delete_response( \WP_REST_Request $request ) {
( new UpdateProducts() )->reset_products_content();
return rest_ensure_response( array( 'removed' => true ) );
}
}

View File

@ -1,4 +1,6 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Routes\V1;
use Automattic\WooCommerce\StoreApi\Utilities\Pagination;

View File

@ -1,4 +1,6 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi;
use Automattic\WooCommerce\StoreApi\Routes\V1\AbstractRoute;
@ -36,7 +38,7 @@ class RoutesController {
public function __construct( SchemaController $schema_controller ) {
$this->schema_controller = $schema_controller;
$this->routes = [
'v1' => [
'v1' => [
Routes\V1\Batch::IDENTIFIER => Routes\V1\Batch::class,
Routes\V1\Cart::IDENTIFIER => Routes\V1\Cart::class,
Routes\V1\CartAddItem::IDENTIFIER => Routes\V1\CartAddItem::class,
@ -66,6 +68,10 @@ class RoutesController {
Routes\V1\ProductsById::IDENTIFIER => Routes\V1\ProductsById::class,
Routes\V1\ProductsBySlug::IDENTIFIER => Routes\V1\ProductsBySlug::class,
],
'private' => [
Routes\V1\AI\Products::IDENTIFIER => Routes\V1\AI\Products::class,
Routes\V1\Patterns::IDENTIFIER => Routes\V1\Patterns::class,
],
];
}

View File

@ -54,6 +54,8 @@ class SchemaController {
Schemas\V1\ProductCategorySchema::IDENTIFIER => Schemas\V1\ProductCategorySchema::class,
Schemas\V1\ProductCollectionDataSchema::IDENTIFIER => Schemas\V1\ProductCollectionDataSchema::class,
Schemas\V1\ProductReviewSchema::IDENTIFIER => Schemas\V1\ProductReviewSchema::class,
Schemas\V1\AI\ProductsSchema::IDENTIFIER => Schemas\V1\AI\ProductsSchema::class,
Schemas\V1\PatternsSchema::IDENTIFIER => Schemas\V1\PatternsSchema::class,
],
];
}

View File

@ -0,0 +1,50 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Schemas\V1\AI;
use Automattic\WooCommerce\StoreApi\Schemas\V1\AbstractSchema;
/**
* ProductsSchema class.
*
* @internal
*/
class ProductsSchema extends AbstractSchema {
/**
* The schema item name.
*
* @var string
*/
protected $title = 'ai/products';
/**
* The schema item identifier.
*
* @var string
*/
const IDENTIFIER = 'ai/products';
/**
* Products schema properties.
*
* @return array
*/
public function get_properties() {
return [];
}
/**
* Get the Products response.
*
* @param array $item Item to get response for.
*
* @return array
*/
public function get_item_response( $item ) {
return [
'ai_content_generated' => $item['ai_content_generated'],
'product_content' => $item['product_content'],
];
}
}

View File

@ -0,0 +1,45 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\StoreApi\Schemas\V1;
/**
* OrderSchema class.
*/
class PatternsSchema extends AbstractSchema {
/**
* The schema item name.
*
* @var string
*/
protected $title = 'patterns';
/**
* The schema item identifier.
*
* @var string
*/
const IDENTIFIER = 'patterns';
/**
* Patterns schema properties.
*
* @return array
*/
public function get_properties() {
return [];
}
/**
* Get the Patterns response.
*
* @param array $item Item to get response for.
*
* @return array
*/
public function get_item_response( $item ) {
return [
'success' => true,
];
}
}

View File

@ -259,7 +259,7 @@ test.describe( 'Homepage tracking banner', () => {
'no'
);
await page.route( '**/wp-json/wc-admin/patterns*', ( route ) => {
await page.route( '**/wp-json/wc/private/patterns*', ( route ) => {
route.fulfill( {
status: 500,
} );

View File

@ -1,121 +0,0 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Admin\API;
use Automattic\WooCommerce\Blocks\Patterns\PTKPatternsStore;
use WC_REST_Unit_Test_Case;
/**
* Patterns Controller Tests.
*/
class PatternsTest extends WC_REST_Unit_Test_Case {
/**
* Set up user for tests.
*/
public function setUp(): void {
parent::setUp();
$user = $this->factory->user->create( array( 'role' => 'administrator' ) );
wp_set_current_user( $user );
}
/**
* Test the post endpoint when tracking is not allowed.
*
* @return void
*/
public function test_post_endpoint_when_tracking_is_not_allowed() {
update_option( 'woocommerce_allow_tracking', 'no' );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'POST', '/wc-admin/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertFalse( $patterns );
}
/**
* Test the post endpoint when tracking is allowed.
*
* @return void
*/
public function test_post_endpoint_when_tracking_is_allowed() {
update_option( 'woocommerce_allow_tracking', 'yes' );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'POST', '/wc-admin/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertNotFalse( $patterns );
}
/**
* Test the get endpoint when tracking is not allowed.
*
* @return void
*/
public function test_get_endpoint_when_tracking_is_not_allowed() {
update_option( 'woocommerce_allow_tracking', 'no' );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc-admin/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertFalse( $patterns );
}
/**
* Test the get endpoint when tracking is allowed.
*
* @return void
*/
public function test_get_endpoint_when_tracking_is_allowed() {
update_option( 'woocommerce_allow_tracking', 'yes' );
rest_get_server()->dispatch( new \WP_REST_Request( 'POST', '/wc-admin/patterns' ) );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc-admin/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertNotFalse( $patterns );
}
/**
* Test the get endpoint when the PTK client fails.
*
* @return void
*/
public function test_get_endpoint_when_ptk_client_fails() {
update_option( 'woocommerce_allow_tracking', 'yes' );
$error = function () {
return new \WP_Error( 'error', 'An error message' );
};
add_filter( 'pre_http_request', $error, 10, 3 );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'GET', '/wc-admin/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 500, $response->get_status() );
$this->assertEquals( 'patterns_toolkit_api_error', $data['code'] );
$this->assertEquals( 'Failed to connect with the Patterns Toolkit API: try again later.', $data['message'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertFalse( $patterns );
}
}

View File

@ -0,0 +1,57 @@
<?php
declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Blocks\StoreApi\Routes;
use Automattic\WooCommerce\Blocks\Patterns\PTKPatternsStore;
/**
* Patterns Controller Tests.
*/
class Patterns extends ControllerTestCase {
/**
* Set up user for tests.
*/
public function setUp(): void {
parent::setUp();
$user = $this->factory->user->create( array( 'role' => 'administrator' ) );
wp_set_current_user( $user );
}
/**
* Test the post endpoint when tracking is not allowed.
*
* @return void
*/
public function test_post_endpoint_when_tracking_is_not_allowed() {
update_option( 'woocommerce_allow_tracking', 'no' );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'POST', '/wc/private/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertFalse( $patterns );
}
/**
* Test the post endpoint when tracking is allowed.
*
* @return void
*/
public function test_post_endpoint_when_tracking_is_allowed() {
update_option( 'woocommerce_allow_tracking', 'yes' );
$response = rest_get_server()->dispatch( new \WP_REST_Request( 'POST', '/wc/private/patterns' ) );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( true, $data['success'] );
$patterns = get_transient( PTKPatternsStore::TRANSIENT_NAME );
$this->assertNotFalse( $patterns );
}
}