Commit 46571c31f27 for woocommerce
commit 46571c31f27a0d58fb6425573b3d7905e0c3220f
Author: Thilina Pituwala <thilina.hasantha@gmail.com>
Date: Fri Nov 20 11:08:00 2026 +1100
Explain why an extension can't be installed when it needs a newer WordPress or PHP (#70902)
* Stop installs that need a newer WordPress or PHP, and say why
The WooCommerce.com installer's move step used install_package(), which
skips WordPress's requirement check, so an extension the site can't run
landed on disk and only failed at activation with a generic error. Check
the package's Requires at least and Requires PHP first, remove the
unpacked files, and fail with the same error codes core uses. My
Subscriptions and the install modal now explain those codes for
installs, the way they already do for updates.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Check an extension's requirements when its destination folder is empty
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Read the unpacked package through its local path
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Check an extension's PHP requirement before its WordPress requirement
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Send the install error code to Tracks the same way as update errors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Check that the empty-folder install tests start with an empty folder
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Check the full requirement error message in the move-product tests
The theme and "needs both" cases didn't check the site's version, and the
plugin cases only checked its first digit. Compare the exact message, built
from PHP_VERSION and wp_get_wp_version() as the installer does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
diff --git a/plugins/woocommerce/changelog/wccom-3194-show-install-requirement-errors b/plugins/woocommerce/changelog/wccom-3194-show-install-requirement-errors
new file mode 100644
index 00000000000..475d7d0ca4e
--- /dev/null
+++ b/plugins/woocommerce/changelog/wccom-3194-show-install-requirement-errors
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Explain when a WooCommerce.com extension can't be installed because it needs a newer WordPress or PHP, and don't leave it on disk.
diff --git a/plugins/woocommerce/client/admin/client/marketplace/components/install-flow/install-new-product-modal.tsx b/plugins/woocommerce/client/admin/client/marketplace/components/install-flow/install-new-product-modal.tsx
index f60d67fc413..0db236ea52a 100644
--- a/plugins/woocommerce/client/admin/client/marketplace/components/install-flow/install-new-product-modal.tsx
+++ b/plugins/woocommerce/client/admin/client/marketplace/components/install-flow/install-new-product-modal.tsx
@@ -16,7 +16,10 @@ import ProductCard from '../product-card/product-card';
import { Product } from '../product-list/types';
import ConnectAccountButton from '../my-subscriptions/table/actions/connect-account-button';
import { installingStore } from '../../contexts/install-store';
-import { downloadProduct } from '../../utils/functions';
+import {
+ downloadProduct,
+ getRequirementErrorNotice,
+} from '../../utils/functions';
import { createOrder } from './create-order';
import { MARKETPLACE_PATH, WP_ADMIN_PLUGIN_LIST_URL } from '../constants';
import { getAdminSetting } from '../../../utils/admin-settings';
@@ -216,6 +219,11 @@ function InstallNewProductModal( props: { products: Product[] } ) {
setNotice( {
status: 'error',
message:
+ getRequirementErrorNotice(
+ 'install',
+ product?.title ?? '',
+ error
+ )?.message ??
error.data.message ??
__(
'An error occurred. Please try again later.',
diff --git a/plugins/woocommerce/client/admin/client/marketplace/components/my-subscriptions/table/actions/install.tsx b/plugins/woocommerce/client/admin/client/marketplace/components/my-subscriptions/table/actions/install.tsx
index c45cbee6a5f..3e6bfa5659b 100644
--- a/plugins/woocommerce/client/admin/client/marketplace/components/my-subscriptions/table/actions/install.tsx
+++ b/plugins/woocommerce/client/admin/client/marketplace/components/my-subscriptions/table/actions/install.tsx
@@ -15,6 +15,8 @@ import { SubscriptionsContext } from '../../../../contexts/subscriptions-context
import {
addNotice,
getInstallUrl,
+ getRequirementErrorNotice,
+ getWpAjaxErrorData,
installProduct,
removeNotice,
} from '../../../../utils/functions';
@@ -58,6 +60,26 @@ export default function Install( props: InstallProps ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleInstallError = ( error: any ) => {
void loadSubscriptions( false ).then( () => {
+ const requirementNotice = getRequirementErrorNotice(
+ 'install',
+ props.subscription.product_name,
+ error
+ );
+ if ( requirementNotice ) {
+ addNotice(
+ props.subscription.product_key,
+ requirementNotice.message,
+ NoticeStatus.Error,
+ { actions: requirementNotice.actions }
+ );
+ stopInstall();
+
+ if ( props.onError ) {
+ props.onError();
+ }
+ return;
+ }
+
let errorMessage = sprintf(
// translators: %s is the product name.
__( '%s couldn’t be installed.', 'woocommerce' ),
@@ -95,6 +117,7 @@ export default function Install( props: InstallProps ) {
product_id: props.subscription.product_id,
product_current_version: props.subscription.version,
error_message: error?.data?.message,
+ error_code: getWpAjaxErrorData( error ).code || '',
} );
};
diff --git a/plugins/woocommerce/client/admin/client/marketplace/utils/functions.tsx b/plugins/woocommerce/client/admin/client/marketplace/utils/functions.tsx
index b928fd46feb..38b5a82ccaa 100644
--- a/plugins/woocommerce/client/admin/client/marketplace/utils/functions.tsx
+++ b/plugins/woocommerce/client/admin/client/marketplace/utils/functions.tsx
@@ -552,27 +552,42 @@ const getRefreshErrorMessage = ( error: unknown ): string => {
};
/**
- * Build the notice for a failed My Subscriptions update, explaining WordPress and PHP requirement failures by error code.
+ * Build the notice for an install or update that failed because the extension needs a newer WordPress or PHP.
+ *
+ * @return The notice, or null when the failure is for another reason.
*/
-const getUpdateErrorNotice = (
+const getRequirementErrorNotice = (
+ operation: 'install' | 'update',
productName: string,
- error: unknown,
- onRetry: () => void
-): { message: string; actions: NoticeAction[] } => {
- const { message: wpMessage, code } = getWpAjaxErrorData( error );
+ error: unknown
+): { message: string; actions: NoticeAction[] } | null => {
+ const { code } = getWpAjaxErrorData( error );
const wccomSettings = getAdminSetting( 'wccomHelper', {} );
+ const isInstall = operation === 'install';
+
switch ( code ) {
- case 'incompatible_wp_required_version':
+ case 'incompatible_wp_required_version': {
+ const message = isInstall
+ ? sprintf(
+ // translators: %s is the product name.
+ __(
+ '%s couldn’t be installed. It requires a newer version of WordPress.',
+ 'woocommerce'
+ ),
+ productName
+ )
+ : sprintf(
+ // translators: %s is the product name.
+ __(
+ '%s couldn’t be updated. This version requires a newer version of WordPress.',
+ 'woocommerce'
+ ),
+ productName
+ );
+
return {
- message: sprintf(
- // translators: %s is the product name.
- __(
- '%s couldn’t be updated. This version requires a newer version of WordPress.',
- 'woocommerce'
- ),
- productName
- ),
+ message,
actions: wccomSettings.updateCoreUrl
? [
{
@@ -582,16 +597,28 @@ const getUpdateErrorNotice = (
]
: [],
};
- case PHP_REQUIREMENT_ERROR_CODE:
+ }
+ case PHP_REQUIREMENT_ERROR_CODE: {
+ const message = isInstall
+ ? sprintf(
+ // translators: %s is the product name.
+ __(
+ '%s couldn’t be installed. It requires a newer version of PHP.',
+ 'woocommerce'
+ ),
+ productName
+ )
+ : sprintf(
+ // translators: %s is the product name.
+ __(
+ '%s couldn’t be updated. This version requires a newer version of PHP.',
+ 'woocommerce'
+ ),
+ productName
+ );
+
return {
- message: sprintf(
- // translators: %s is the product name.
- __(
- '%s couldn’t be updated. This version requires a newer version of PHP.',
- 'woocommerce'
- ),
- productName
- ),
+ message,
actions: wccomSettings.updatePhpUrl
? [
{
@@ -602,8 +629,31 @@ const getUpdateErrorNotice = (
]
: [],
};
+ }
}
+ return null;
+};
+
+/**
+ * Build the notice for a failed My Subscriptions update, explaining WordPress and PHP requirement failures by error code.
+ */
+const getUpdateErrorNotice = (
+ productName: string,
+ error: unknown,
+ onRetry: () => void
+): { message: string; actions: NoticeAction[] } => {
+ const requirementNotice = getRequirementErrorNotice(
+ 'update',
+ productName,
+ error
+ );
+ if ( requirementNotice ) {
+ return requirementNotice;
+ }
+
+ const { message: wpMessage } = getWpAjaxErrorData( error );
+
let message = sprintf(
// translators: %s is the product name.
__( '%s couldn’t be updated.', 'woocommerce' ),
@@ -739,6 +789,7 @@ export {
updateProduct,
addNotice,
getRefreshErrorMessage,
+ getRequirementErrorNotice,
getUpdateErrorNotice,
getWpAjaxErrorData,
PHP_REQUIREMENT_ERROR_CODE,
diff --git a/plugins/woocommerce/client/admin/client/marketplace/utils/test/get-requirement-error-notice.test.ts b/plugins/woocommerce/client/admin/client/marketplace/utils/test/get-requirement-error-notice.test.ts
new file mode 100644
index 00000000000..0d5539edc25
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/marketplace/utils/test/get-requirement-error-notice.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Internal dependencies
+ */
+import { getRequirementErrorNotice } from '../functions';
+
+const mockSettings: Record< string, string > = {};
+
+jest.mock( '~/utils/admin-settings', () => ( {
+ getAdminSetting: () => mockSettings,
+} ) );
+
+const reject = ( code: string, message: string ) => ( {
+ success: false,
+ data: { code, message },
+} );
+
+describe( 'getRequirementErrorNotice', () => {
+ beforeEach( () => {
+ mockSettings.updateCoreUrl =
+ 'https://example.test/wp-admin/update-core.php';
+ mockSettings.updatePhpUrl = 'https://wordpress.org/support/update-php/';
+ } );
+
+ it( 'explains an install that needs a newer WordPress, with a link to update it', () => {
+ expect(
+ getRequirementErrorNotice(
+ 'install',
+ 'Product Bundles',
+ reject(
+ 'incompatible_wp_required_version',
+ 'The package could not be installed.'
+ )
+ )
+ ).toEqual( {
+ message:
+ 'Product Bundles couldn’t be installed. It requires a newer version of WordPress.',
+ actions: [
+ {
+ label: 'Update WordPress',
+ url: 'https://example.test/wp-admin/update-core.php',
+ },
+ ],
+ } );
+ } );
+
+ it( 'explains an install that needs a newer PHP, with a link to learn more', () => {
+ expect(
+ getRequirementErrorNotice(
+ 'install',
+ 'Product Bundles',
+ reject(
+ 'incompatible_php_required_version',
+ 'The package could not be installed.'
+ )
+ )
+ ).toEqual( {
+ message:
+ 'Product Bundles couldn’t be installed. It requires a newer version of PHP.',
+ actions: [
+ {
+ label: 'Learn more',
+ url: 'https://wordpress.org/support/update-php/',
+ openInNewTab: true,
+ },
+ ],
+ } );
+ } );
+
+ it( 'shows no action when the user can’t update WordPress', () => {
+ mockSettings.updateCoreUrl = '';
+
+ expect(
+ getRequirementErrorNotice(
+ 'install',
+ 'Product Bundles',
+ reject( 'incompatible_wp_required_version', '' )
+ )?.actions
+ ).toEqual( [] );
+ } );
+
+ it( 'keeps the update wording for updates', () => {
+ expect(
+ getRequirementErrorNotice(
+ 'update',
+ 'Product Bundles',
+ reject( 'incompatible_wp_required_version', '' )
+ )?.message
+ ).toBe(
+ 'Product Bundles couldn’t be updated. This version requires a newer version of WordPress.'
+ );
+ } );
+
+ it.each( [
+ [
+ 'another error code',
+ reject( 'folder_exists', 'Destination folder already exists.' ),
+ ],
+ [ 'no error code', { success: false, data: { message: 'Oops' } } ],
+ [ 'a string', 'Please reload and try again' ],
+ [ 'undefined', undefined ],
+ ] )( 'returns null for %s', ( _label, error ) => {
+ expect(
+ getRequirementErrorNotice( 'install', 'Product Bundles', error )
+ ).toBeNull();
+ } );
+} );
diff --git a/plugins/woocommerce/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product.php b/plugins/woocommerce/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product.php
index 461b2710f41..005d64f639e 100644
--- a/plugins/woocommerce/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product.php
+++ b/plugins/woocommerce/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product.php
@@ -43,6 +43,8 @@ class WC_WCCOM_Site_Installation_Step_Move_Product implements WC_WCCOM_Site_Inst
? WP_PLUGIN_DIR
: get_theme_root();
+ $this->check_package_requirements( $destination );
+
$package = array(
'source' => $this->state->get_unpacked_path(),
'destination' => $destination,
@@ -79,6 +81,168 @@ class WC_WCCOM_Site_Installation_Step_Move_Product implements WC_WCCOM_Site_Inst
return $this->state;
}
+ /**
+ * Stops the install when the package needs a newer WordPress or PHP than the site runs.
+ *
+ * WP_Upgrader::install_package() doesn't run the requirement check WordPress runs on an upload, so without
+ * this the extension lands on disk and only fails when it's activated, with a generic error.
+ * A copy that's already installed is left to the existing folder_exists handling.
+ *
+ * @since 11.4.0
+ * @param string $destination The plugins or themes directory the package installs into.
+ * @return void
+ * @throws WC_REST_WCCOM_Site_Installer_Error If the site doesn't meet the package's requirements.
+ */
+ protected function check_package_requirements( string $destination ): void {
+ $source = $this->get_package_root( $this->get_local_path( (string) $this->state->get_unpacked_path() ) );
+ if ( '' === $source || $this->is_installed_copy( trailingslashit( $destination ) . basename( $source ) ) ) {
+ return;
+ }
+
+ $headers = $this->get_package_headers( $source );
+
+ // PHP first, as Plugin_Upgrader::check_package() does: a newer WordPress may itself need a newer PHP.
+ if ( ! is_php_version_compatible( $headers['RequiresPHP'] ) ) {
+ $this->delete_unpacked_package();
+ // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- The code is a static string; the message is escaped below.
+ throw new Installer_Error(
+ Installer_Error_Codes::INCOMPATIBLE_PHP_REQUIRED_VERSION,
+ esc_html(
+ sprintf(
+ /* translators: 1: PHP version the extension needs, 2: PHP version the server runs. */
+ __( 'This extension needs PHP %1$s or later, and this server runs PHP %2$s.', 'woocommerce' ),
+ $headers['RequiresPHP'],
+ PHP_VERSION
+ )
+ )
+ );
+ // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
+ }
+
+ if ( ! is_wp_version_compatible( $headers['RequiresWP'] ) ) {
+ $this->delete_unpacked_package();
+ // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- The code is a static string; the message is escaped below.
+ throw new Installer_Error(
+ Installer_Error_Codes::INCOMPATIBLE_WP_REQUIRED_VERSION,
+ esc_html(
+ sprintf(
+ /* translators: 1: WordPress version the extension needs, 2: WordPress version the site runs. */
+ __( 'This extension needs WordPress %1$s or later, and this site runs WordPress %2$s.', 'woocommerce' ),
+ $headers['RequiresWP'],
+ wp_get_wp_version()
+ )
+ )
+ );
+ // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
+ }
+ }
+
+ /**
+ * Whether a copy is already installed at the path, using the same test as install_package()'s folder_exists check.
+ *
+ * An empty folder doesn't count: install_package() installs into it, so the requirements still need checking.
+ *
+ * @since 11.4.0
+ * @param string $path Where the package would be installed, as a local path.
+ * @return bool
+ */
+ private function is_installed_copy( string $path ): bool {
+ return file_exists( $path ) && ( ! is_dir( $path ) || array() !== array_diff( (array) scandir( $path ), array( '.', '..' ) ) );
+ }
+
+ /**
+ * Turns a WP_Filesystem path into the local path PHP's own file functions can read, as Plugin_Upgrader::check_package() does.
+ *
+ * Over FTP or SSH the filesystem's root can differ from the local one, so the unpacked package's path doesn't
+ * work with is_dir() and friends until it's mapped back.
+ *
+ * @since 11.4.0
+ * @param string $path A path from WP_Filesystem, such as the unpacked package's.
+ * @return string
+ */
+ private function get_local_path( string $path ): string {
+ global $wp_filesystem;
+
+ if ( '' === $path || ! $wp_filesystem instanceof WP_Filesystem_Base ) {
+ return $path;
+ }
+
+ return str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $path );
+ }
+
+ /**
+ * Gets the directory that holds the plugin or theme files, the way install_package() picks it.
+ *
+ * @since 11.4.0
+ * @param string $unpacked_path The directory the package was unpacked into.
+ * @return string The directory, or an empty string when there's nothing to read.
+ */
+ private function get_package_root( string $unpacked_path ): string {
+ if ( '' === $unpacked_path || ! is_dir( $unpacked_path ) ) {
+ return '';
+ }
+
+ $entries = array_values( array_diff( (array) scandir( $unpacked_path ), array( '.', '..' ) ) );
+ if ( 1 === count( $entries ) && is_dir( trailingslashit( $unpacked_path ) . $entries[0] ) ) {
+ return trailingslashit( $unpacked_path ) . $entries[0];
+ }
+
+ return untrailingslashit( $unpacked_path );
+ }
+
+ /**
+ * Reads the WordPress and PHP requirements from the package's plugin or theme headers.
+ *
+ * @since 11.4.0
+ * @param string $source The directory that holds the plugin or theme files.
+ * @return array{RequiresWP: string, RequiresPHP: string}
+ */
+ private function get_package_headers( string $source ): array {
+ $fields = array(
+ 'Name' => 'plugin' === $this->state->get_product_type() ? 'Plugin Name' : 'Theme Name',
+ 'RequiresWP' => 'Requires at least',
+ 'RequiresPHP' => 'Requires PHP',
+ );
+
+ $files = 'plugin' === $this->state->get_product_type()
+ ? array_filter( (array) glob( trailingslashit( $source ) . '*.php' ), 'is_string' )
+ : array( trailingslashit( $source ) . 'style.css' );
+
+ foreach ( $files as $file ) {
+ if ( ! is_string( $file ) || ! is_file( $file ) ) {
+ continue;
+ }
+
+ $headers = get_file_data( $file, $fields );
+ if ( '' !== $headers['Name'] ) {
+ return array(
+ 'RequiresWP' => $headers['RequiresWP'],
+ 'RequiresPHP' => $headers['RequiresPHP'],
+ );
+ }
+ }
+
+ return array(
+ 'RequiresWP' => '',
+ 'RequiresPHP' => '',
+ );
+ }
+
+ /**
+ * Removes the unpacked package, as install_package() would after installing it.
+ *
+ * @since 11.4.0
+ * @return void
+ */
+ private function delete_unpacked_package(): void {
+ global $wp_filesystem;
+
+ $unpacked_path = (string) $this->state->get_unpacked_path();
+ if ( '' !== $unpacked_path && $wp_filesystem instanceof WP_Filesystem_Base ) {
+ $wp_filesystem->delete( $unpacked_path, true );
+ }
+ }
+
/**
* Connect to wccom if installing a theme
*
diff --git a/plugins/woocommerce/includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error-codes.php b/plugins/woocommerce/includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error-codes.php
index 9e970af7b65..cdc139f0ec6 100644
--- a/plugins/woocommerce/includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error-codes.php
+++ b/plugins/woocommerce/includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error-codes.php
@@ -40,6 +40,8 @@ class WC_REST_WCCOM_Site_Installer_Error_Codes {
const MISSING_UNPACKED_PATH = 'missing_unpacked_path';
const UNKNOWN_FILENAME = 'unknown_filename';
const PLUGIN_ACTIVATION_ERROR = 'plugin_activation_error';
+ const INCOMPATIBLE_WP_REQUIRED_VERSION = 'incompatible_wp_required_version';
+ const INCOMPATIBLE_PHP_REQUIRED_VERSION = 'incompatible_php_required_version';
const UNEXPECTED_ERROR = 'unexpected_error';
const FAILED_TO_RESET_INSTALLATION_STATE = 'failed_to_reset_installation_state';
@@ -68,6 +70,8 @@ class WC_REST_WCCOM_Site_Installer_Error_Codes {
self::MISSING_UNPACKED_PATH => 'Unpacked path is missing',
self::UNKNOWN_FILENAME => 'Unknown product filename',
self::PLUGIN_ACTIVATION_ERROR => 'Plugin activation error',
+ self::INCOMPATIBLE_WP_REQUIRED_VERSION => 'The product requires a newer version of WordPress',
+ self::INCOMPATIBLE_PHP_REQUIRED_VERSION => 'The product requires a newer version of PHP',
self::UNEXPECTED_ERROR => 'Unexpected error',
self::FAILED_TO_RESET_INSTALLATION_STATE => 'Failed to reset installation state',
);
diff --git a/plugins/woocommerce/tests/php/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product-test.php b/plugins/woocommerce/tests/php/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product-test.php
new file mode 100644
index 00000000000..f3a237a3bb6
--- /dev/null
+++ b/plugins/woocommerce/tests/php/includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product-test.php
@@ -0,0 +1,316 @@
+<?php
+declare( strict_types = 1 );
+
+/**
+ * Tests for WC_WCCOM_Site_Installation_Step_Move_Product.
+ */
+class WC_WCCOM_Site_Installation_Step_Move_Product_Test extends WC_Unit_Test_Case {
+
+ private const SLUG = 'wc-move-product-test-extension';
+
+ /**
+ * Directory the fixture package is unpacked into.
+ *
+ * @var string
+ */
+ private $unpacked_path;
+
+ /**
+ * Load the installer classes, which WooCommerce only loads for WooCommerce.com requests.
+ */
+ public static function setUpBeforeClass(): void {
+ parent::setUpBeforeClass();
+
+ require_once ABSPATH . 'wp-admin/includes/plugin.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/class-wc-wccom-site-installer.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error-codes.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-error.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/installation/class-wc-wccom-site-installation-state.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/installation/installation-steps/interface-installaton-step.php';
+ require_once WC_ABSPATH . 'includes/wccom-site/installation/installation-steps/class-wc-wccom-site-installation-step-move-product.php';
+ }
+
+ /**
+ * Set up before each test.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->unpacked_path = trailingslashit( WP_CONTENT_DIR ) . 'upgrade/' . self::SLUG . '-' . wp_generate_password( 8, false );
+ }
+
+ /**
+ * Tear down after each test.
+ */
+ public function tearDown(): void {
+ try {
+ // Files on disk, which the database rollback doesn't cover.
+ foreach ( array( $this->unpacked_path, WP_PLUGIN_DIR . '/' . self::SLUG, get_theme_root() . '/' . self::SLUG ) as $dir ) {
+ $this->delete_dir( $dir );
+ }
+ wp_clean_plugins_cache();
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * Requirements a package can declare, and the error the step should report.
+ *
+ * @return array
+ */
+ public function unmet_requirements(): array {
+ return array(
+ 'plugin needing a newer WordPress' => array( 'plugin', '99.0', '', 'incompatible_wp_required_version' ),
+ 'plugin needing a newer PHP' => array( 'plugin', '', '99.0', 'incompatible_php_required_version' ),
+ 'theme needing a newer WordPress' => array( 'theme', '99.0', '', 'incompatible_wp_required_version' ),
+ 'theme needing a newer PHP' => array( 'theme', '', '99.0', 'incompatible_php_required_version' ),
+ // PHP is reported first, as WordPress core does.
+ 'plugin needing both' => array( 'plugin', '99.0', '99.0', 'incompatible_php_required_version' ),
+ 'theme needing both' => array( 'theme', '99.0', '99.0', 'incompatible_php_required_version' ),
+ );
+ }
+
+ /**
+ * @testdox The step stops before installing a package the site can't run, and says why: $_dataName.
+ * @dataProvider unmet_requirements
+ *
+ * @param string $type 'plugin' or 'theme'.
+ * @param string $requires_wp Requires at least header.
+ * @param string $requires_php Requires PHP header.
+ * @param string $expected_code Expected installer error code.
+ */
+ public function test_stops_install_when_requirements_are_not_met( string $type, string $requires_wp, string $requires_php, string $expected_code ): void {
+ $this->unpack_fixture( $type, $requires_wp, $requires_php );
+
+ $error = null;
+ try {
+ ( new WC_WCCOM_Site_Installation_Step_Move_Product( $this->state( $type ) ) )->run();
+ } catch ( WC_REST_WCCOM_Site_Installer_Error $e ) {
+ $error = $e;
+ }
+
+ $this->assertNotNull( $error, 'The step should fail' );
+ $this->assertSame( $expected_code, $error->get_error_code() );
+ $expected_message = 'incompatible_php_required_version' === $expected_code
+ ? 'This extension needs PHP 99.0 or later, and this server runs PHP ' . PHP_VERSION . '.'
+ : 'This extension needs WordPress 99.0 or later, and this site runs WordPress ' . wp_get_wp_version() . '.';
+ $this->assertSame( $expected_message, $error->get_error_message(), 'The message should name the required and the current version' );
+ $this->assertDirectoryDoesNotExist( $this->destination( $type ), 'Nothing should be installed' );
+ $this->assertDirectoryDoesNotExist( $this->unpacked_path, 'The unpacked package should be removed' );
+ }
+
+ /**
+ * @testdox The step installs a package whose requirements the site meets, or that declares none.
+ * @testWith ["1.0", "5.6"]
+ * ["", ""]
+ *
+ * @param string $requires_wp Requires at least header.
+ * @param string $requires_php Requires PHP header.
+ */
+ public function test_installs_when_requirements_are_met( string $requires_wp, string $requires_php ): void {
+ $this->unpack_fixture( 'plugin', $requires_wp, $requires_php );
+
+ $state = ( new WC_WCCOM_Site_Installation_Step_Move_Product( $this->state( 'plugin' ) ) )->run();
+
+ $this->assertFileExists( $this->destination( 'plugin' ) . '/' . self::SLUG . '.php' );
+ $this->assertSame( trailingslashit( $this->destination( 'plugin' ) ), trailingslashit( $state->get_installed_path() ) );
+ }
+
+ /**
+ * @testdox A copy that's already installed is reused, even when the new package needs a newer WordPress.
+ */
+ public function test_reuses_an_installed_copy_without_checking_the_new_package(): void {
+ $this->write_extension( 'plugin', $this->destination( 'plugin' ), '', '' );
+ wp_clean_plugins_cache();
+ $this->unpack_fixture( 'plugin', '99.0', '' );
+
+ $state = ( new WC_WCCOM_Site_Installation_Step_Move_Product( $this->state( 'plugin' ) ) )->run();
+
+ $this->assertSame( trailingslashit( $this->destination( 'plugin' ) ), trailingslashit( $state->get_installed_path() ), 'The installed copy should be used, as before' );
+ }
+
+ /**
+ * @testdox An empty folder left at the destination isn't an installed copy, so a package the site can't run is still stopped.
+ */
+ public function test_stops_install_into_an_empty_destination_folder(): void {
+ $this->make_empty_destination( 'plugin' );
+ $this->unpack_fixture( 'plugin', '99.0', '' );
+
+ $error = null;
+ try {
+ ( new WC_WCCOM_Site_Installation_Step_Move_Product( $this->state( 'plugin' ) ) )->run();
+ } catch ( WC_REST_WCCOM_Site_Installer_Error $e ) {
+ $error = $e;
+ }
+
+ $this->assertNotNull( $error, 'The step should fail' );
+ $this->assertSame( 'incompatible_wp_required_version', $error->get_error_code() );
+ $this->assertFileDoesNotExist( $this->destination( 'plugin' ) . '/' . self::SLUG . '.php', 'Nothing should be installed' );
+ }
+
+ /**
+ * @testdox The requirements are still checked when WordPress writes files over FTP or SSH, where the filesystem's root differs from the local one.
+ */
+ public function test_checks_requirements_when_the_filesystem_root_differs(): void {
+ global $wp_filesystem;
+
+ $this->unpack_fixture( 'plugin', '99.0', '' );
+ WC_WCCOM_Site_Installer::get_wp_upgrader(); // Sets up WP_Filesystem, so the stand-in below isn't replaced.
+
+ $remote_content_dir = '/remote-root/wp-content/';
+ $state = $this->state( 'plugin' );
+ $state->set_unpacked_path( str_replace( trailingslashit( WP_CONTENT_DIR ), $remote_content_dir, $this->unpacked_path ) );
+
+ $original_filesystem = $wp_filesystem;
+ // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Stand-in for an FTP filesystem, restored below.
+ $wp_filesystem = new class( null, $remote_content_dir ) extends WP_Filesystem_Direct {
+ /**
+ * The content directory as the filesystem sees it.
+ *
+ * @var string
+ */
+ private $remote_content_dir;
+
+ /**
+ * Constructor.
+ *
+ * @param mixed $arg Unused.
+ * @param string $remote_content_dir The content directory as the filesystem sees it.
+ */
+ public function __construct( $arg, string $remote_content_dir ) {
+ parent::__construct( $arg );
+ $this->remote_content_dir = $remote_content_dir;
+ }
+
+ /**
+ * The content directory as the filesystem sees it.
+ *
+ * @return string
+ */
+ public function wp_content_dir() {
+ return $this->remote_content_dir;
+ }
+ };
+
+ $error = null;
+ try {
+ ( new WC_WCCOM_Site_Installation_Step_Move_Product( $state ) )->run();
+ } catch ( WC_REST_WCCOM_Site_Installer_Error $e ) {
+ $error = $e;
+ } finally {
+ // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restoring the original filesystem.
+ $wp_filesystem = $original_filesystem;
+ }
+
+ $this->assertNotNull( $error, 'The step should fail' );
+ $this->assertSame( 'incompatible_wp_required_version', $error->get_error_code() );
+ $this->assertDirectoryDoesNotExist( $this->destination( 'plugin' ), 'Nothing should be installed' );
+ }
+
+ /**
+ * @testdox A package whose requirements the site meets installs into an empty destination folder, as WordPress does.
+ */
+ public function test_installs_into_an_empty_destination_folder(): void {
+ $this->make_empty_destination( 'plugin' );
+ $this->unpack_fixture( 'plugin', '1.0', '' );
+
+ $state = ( new WC_WCCOM_Site_Installation_Step_Move_Product( $this->state( 'plugin' ) ) )->run();
+
+ $this->assertFileExists( $this->destination( 'plugin' ) . '/' . self::SLUG . '.php' );
+ $this->assertSame( trailingslashit( $this->destination( 'plugin' ) ), trailingslashit( $state->get_installed_path() ) );
+ }
+
+ /**
+ * Installation state for the fixture product.
+ *
+ * @param string $type 'plugin' or 'theme'.
+ * @return WC_WCCOM_Site_Installation_State
+ */
+ private function state( string $type ): WC_WCCOM_Site_Installation_State {
+ $state = WC_WCCOM_Site_Installation_State::initiate_new( 123, 'test-key' );
+ $state->set_product_type( $type );
+ $state->set_unpacked_path( $this->unpacked_path );
+
+ return $state;
+ }
+
+ /**
+ * Where the fixture would be installed.
+ *
+ * @param string $type 'plugin' or 'theme'.
+ * @return string
+ */
+ private function destination( string $type ): string {
+ return ( 'plugin' === $type ? WP_PLUGIN_DIR : get_theme_root() ) . '/' . self::SLUG;
+ }
+
+ /**
+ * Create an empty folder where the fixture would be installed, and check it's really there and empty.
+ *
+ * Without the check, a failed mkdir would leave the tests covering a missing folder instead.
+ *
+ * @param string $type 'plugin' or 'theme'.
+ */
+ private function make_empty_destination( string $type ): void {
+ $dir = $this->destination( $type );
+ wp_mkdir_p( $dir );
+
+ $this->assertDirectoryExists( $dir, 'The empty destination folder should exist before the install' );
+ $this->assertSame( array(), array_values( array_diff( (array) scandir( $dir ), array( '.', '..' ) ) ), 'The destination folder should start empty' );
+ }
+
+ /**
+ * Lay out an unpacked package, as WP_Upgrader::unpack_package() leaves it.
+ *
+ * @param string $type 'plugin' or 'theme'.
+ * @param string $requires_wp Requires at least header.
+ * @param string $requires_php Requires PHP header.
+ */
+ private function unpack_fixture( string $type, string $requires_wp, string $requires_php ): void {
+ $this->write_extension( $type, $this->unpacked_path . '/' . self::SLUG, $requires_wp, $requires_php );
+ }
+
+ /**
+ * Write a minimal plugin or theme.
+ *
+ * @param string $type 'plugin' or 'theme'.
+ * @param string $dir Directory to write into.
+ * @param string $requires_wp Requires at least header.
+ * @param string $requires_php Requires PHP header.
+ */
+ private function write_extension( string $type, string $dir, string $requires_wp, string $requires_php ): void {
+ wp_mkdir_p( $dir );
+
+ $headers = '' !== $requires_wp ? " * Requires at least: {$requires_wp}\n" : '';
+ $headers .= '' !== $requires_php ? " * Requires PHP: {$requires_php}\n" : '';
+
+ // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Test fixtures.
+ if ( 'plugin' === $type ) {
+ file_put_contents( $dir . '/' . self::SLUG . '.php', "<?php\n/**\n * Plugin Name: Move product test extension\n * Version: 1.0.0\n{$headers} */\n" );
+ } else {
+ file_put_contents( $dir . '/style.css', "/*\n * Theme Name: Move product test extension\n * Version: 1.0.0\n{$headers} */\n" );
+ file_put_contents( $dir . '/index.php', "<?php\n" );
+ }
+ // phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+ }
+
+ /**
+ * Delete a fixture directory.
+ *
+ * @param string $dir Directory to delete.
+ */
+ private function delete_dir( string $dir ): void {
+ global $wp_filesystem;
+
+ if ( ! is_dir( $dir ) ) {
+ return;
+ }
+
+ if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
+ require_once ABSPATH . 'wp-admin/includes/file.php';
+ WP_Filesystem();
+ }
+
+ $wp_filesystem->delete( $dir, true );
+ }
+}