Commit 3ec2b4450a8 for woocommerce
commit 3ec2b4450a8379e3d6bdebeed7df8bff8975d618
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date: Thu Nov 19 11:11:56 2026 +0200
Add wp wc product export CLI command (#70690)
* feat: add wp wc product export CLI command
* test: compare temp listings so other runs' leftovers can't fail cleanup tests
* fix: refuse empty export filters and document that --ids overrides them
* fix: keep 0 in export ID lists so --ids=0 is rejected, not dropped
* fix: list filtered export column names so --columns accepts them
* fix: reject directory export targets; keep porcelain output with --quiet
* fix: free export caches per batch and restore the cache suspend state
diff --git a/docs/wc-cli/wc-cli-commands/README.md b/docs/wc-cli/wc-cli-commands/README.md
index 588d321b96b..4f28f8587f8 100644
--- a/docs/wc-cli/wc-cli-commands/README.md
+++ b/docs/wc-cli/wc-cli-commands/README.md
@@ -37,6 +37,7 @@ wp wc [command] --help
| [wc palt](/docs/wc-cli/wc-cli-commands/wc-palt/) | Commands for managing the product attributes lookup table. The table stores denormalized product attribute term data used to speed up catalog filtering. |
| [wc payment_gateway](/docs/wc-cli/wc-cli-commands/wc-payment-gateway/) | Manage WooCommerce payment gateway resources. |
| [wc product](/docs/wc-cli/wc-cli-commands/wc-product/) | Manage WooCommerce product resources. |
+| [wc product export](/docs/wc-cli/wc-cli-commands/wc-product-export/) | Export products to a CSV file using the same engine as the admin product exporter. |
| [wc product_attribute](/docs/wc-cli/wc-cli-commands/wc-product-attribute/) | Manage WooCommerce product attribute resources. |
| [wc product_attribute_term](/docs/wc-cli/wc-cli-commands/wc-product-attribute-term/) | Manage WooCommerce product attribute term resources. |
| [wc product_cat](/docs/wc-cli/wc-cli-commands/wc-product-cat/) | Manage WooCommerce product category resources. |
diff --git a/docs/wc-cli/wc-cli-commands/wc-product-export.md b/docs/wc-cli/wc-cli-commands/wc-product-export.md
new file mode 100644
index 00000000000..e59b75d4bef
--- /dev/null
+++ b/docs/wc-cli/wc-cli-commands/wc-product-export.md
@@ -0,0 +1,40 @@
+---
+title: wc product export
+sidebar_label: wc product export
+---
+
+Export products to a CSV file using the same underlying engine as the admin product exporter
+(**WooCommerce > Products > Export**).
+
+## wc product export `[<file>]`
+
+Export products to a CSV file, or `-` to print the CSV to STDOUT. Required unless `--list-columns`
+is used.
+
+- `--columns=<list>` - Comma-separated column keys to export. Defaults to all. Use `--list-columns` to see keys.
+- `--types=<list>` - Comma-separated product types, such as simple, variable, variation, grouped, and external. Also accepts types registered by extensions or added through `woocommerce_exporter_product_types`. Defaults to all.
+- `--category=<list>` - Comma-separated category slugs.
+- `--ids=<list>` - Comma-separated product IDs. Takes priority over `--types` and `--category`, which are ignored. A variable product's variations are included.
+- `--meta` - Include custom meta columns.
+- `--batch-size=<n>` - Products per batch.
+
+ Default: `50`
+
+- `--list-columns` - Print available column keys and labels, then exit.
+- `--porcelain` - Print only the number of exported products. Cannot be used with `-`.
+
+### Examples
+
+```bash
+# List the available column keys.
+wp wc product export --list-columns
+
+# Export every simple product to a file.
+wp wc product export products.csv --types=simple
+
+# Export a specific set of products and columns, including meta.
+wp wc product export products.csv --ids=12,34,56 --columns=id,sku,name --meta
+
+# Export to STDOUT and pipe it elsewhere.
+wp wc product export - --types=simple | gzip > products.csv.gz
+```
diff --git a/plugins/woocommerce/changelog/add-wc-cli-product-export b/plugins/woocommerce/changelog/add-wc-cli-product-export
new file mode 100644
index 00000000000..e1dac1a13bc
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-wc-cli-product-export
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add a `wp wc product export` WP-CLI command that reuses the existing product CSV exporter.
diff --git a/plugins/woocommerce/includes/class-wc-cli.php b/plugins/woocommerce/includes/class-wc-cli.php
index b3339e499d1..22091cdb608 100644
--- a/plugins/woocommerce/includes/class-wc-cli.php
+++ b/plugins/woocommerce/includes/class-wc-cli.php
@@ -11,6 +11,7 @@ use Automattic\WooCommerce\Internal\ProductAttributesLookup\CLIRunner as Product
use Automattic\WooCommerce\Internal\Integrations\WPPostsImporter;
use Automattic\WooCommerce\Utilities\FeaturesUtil;
use Automattic\WooCommerce\Internal\CLI\Migrator\Runner;
+use Automattic\WooCommerce\Internal\CLI\ImportExport\Product\Runner as ProductImportExportCLIRunner;
defined( 'ABSPATH' ) || exit;
@@ -75,6 +76,9 @@ class WC_CLI {
WP_CLI::add_hook( 'after_wp_load', array( $cli_runner, 'register_commands' ) );
$cli_runner = wc_get_container()->get( ProductAttributesLookupCLIRunner::class );
WP_CLI::add_hook( 'after_wp_load', fn() => \WP_CLI::add_command( 'wc palt', $cli_runner ) );
+ $cli_runner = wc_get_container()->get( ProductImportExportCLIRunner::class );
+ // @phpstan-ignore-next-line class.notFound
+ WP_CLI::add_hook( 'after_wp_load', array( $cli_runner, 'register_commands' ) );
}
/**
diff --git a/plugins/woocommerce/includes/export/class-wc-product-csv-exporter.php b/plugins/woocommerce/includes/export/class-wc-product-csv-exporter.php
index 5d6274be041..61bae764f67 100644
--- a/plugins/woocommerce/includes/export/class-wc-product-csv-exporter.php
+++ b/plugins/woocommerce/includes/export/class-wc-product-csv-exporter.php
@@ -103,7 +103,7 @@ class WC_Product_CSV_Exporter extends WC_CSV_Batch_Exporter {
/**
* Product category to export
*
- * @param string $product_category_to_export Product category slug to export, empty string exports all.
+ * @param string[] $product_category_to_export Product category slugs to export, empty array exports all.
*
* @since 3.5.0
* @return void
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 3e059e005e6..776a1794128 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -1968,12 +1968,6 @@ parameters:
count: 2
path: includes/admin/class-wc-admin-exporters.php
- -
- message: '#^Parameter \#1 \$product_category_to_export of method WC_Product_CSV_Exporter\:\:set_product_category_to_export\(\) expects string, list\<mixed\> given\.$#'
- identifier: argument.type
- count: 1
- path: includes/admin/class-wc-admin-exporters.php
-
-
message: '#^Property WC_Admin_Exporters\:\:\$exporters \(array\<string\>\) does not accept array\<array\<string, list\<\$this\(WC_Admin_Exporters\)\|string\>\|string\>\|string\>\.$#'
identifier: assign.propertyType
@@ -18846,12 +18840,6 @@ parameters:
count: 1
path: includes/export/class-wc-product-csv-exporter.php
- -
- message: '#^Parameter \#2 \$array of function array_map expects array, string given\.$#'
- identifier: argument.type
- count: 1
- path: includes/export/class-wc-product-csv-exporter.php
-
-
message: '#^@param object \$order does not accept actual type of parameter\: WC_Order\|WC_Order_Refund\|false\.$#'
identifier: parameter.phpDocType
diff --git a/plugins/woocommerce/phpstan.neon b/plugins/woocommerce/phpstan.neon
index ebdabb21e3f..510ee841afc 100644
--- a/plugins/woocommerce/phpstan.neon
+++ b/plugins/woocommerce/phpstan.neon
@@ -90,6 +90,11 @@ parameters:
identifier: woocommerce.stagedWrite
message: '#^Method WC_Shipping_Zone::add_shipping_method\(\) writes outside save\(\)\.#'
path: includes/class-wc-shipping-zone.php
+ # PHPStan has no WP-CLI stubs, so it cannot see WP_CLI or its helper functions. Remove once stubs are added.
+ -
+ message: '#unknown class WP_CLI|Function WP_CLI\\Utils\\\w+ not found#'
+ paths:
+ - src/Internal/CLI/ImportExport/Product/ExportCommand.php
parallel:
maximumNumberOfProcesses: 4
diff --git a/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/CsvExporter.php b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/CsvExporter.php
new file mode 100644
index 00000000000..3993ab07871
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/CsvExporter.php
@@ -0,0 +1,63 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Admin\ImportExport\Product;
+
+use WC_Product_CSV_Exporter;
+
+/**
+ * Subclasses `WC_Product_CSV_Exporter` for runners with no admin request behind them,
+ * such as WP-CLI.
+ *
+ * Writes its temporary CSV and headers files to `get_temp_dir()` instead of the uploads
+ * directory the admin export flow uses. `ProductExporter` refuses to run when that directory
+ * resolves inside the web root.
+ *
+ * @since 11.4.0
+ */
+final class CsvExporter extends WC_Product_CSV_Exporter {
+
+ /**
+ * Rows written by pages before the current one.
+ *
+ * @var int
+ */
+ private int $rows_in_earlier_pages = 0;
+
+ /**
+ * Set the page, banking the rows of the page just finished.
+ *
+ * `ProductExporter` reuses one instance across pages, but the parent resets `exported_row_count`
+ * only per request, so the count would otherwise carry over from page to page.
+ *
+ * @param int $page Page number.
+ */
+ public function set_page( $page ): void {
+ $this->rows_in_earlier_pages += $this->exported_row_count;
+ $this->exported_row_count = 0;
+
+ parent::set_page( $page );
+ }
+
+ /**
+ * Get the number of rows exported across all pages so far.
+ *
+ * The parent assumes one instance per page. `get_percent_complete()` still calls the parent
+ * version directly, which sees only the current page's rows, as in an admin request.
+ *
+ * @return int
+ */
+ public function get_total_exported() {
+ return $this->rows_in_earlier_pages + $this->exported_row_count;
+ }
+
+ /**
+ * Get file path to export to.
+ *
+ * @return string
+ */
+ public function get_file_path() {
+ return get_temp_dir() . $this->get_filename();
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ProductExporter.php b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ProductExporter.php
new file mode 100644
index 00000000000..1c1ca6ef137
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ProductExporter.php
@@ -0,0 +1,247 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Admin\ImportExport\Product;
+
+use Automattic\WooCommerce\Internal\Admin\ImportExport\TempDirectoryGuard;
+use Automattic\WooCommerce\Internal\ProductFeed\Utils\MemoryManager;
+use InvalidArgumentException;
+use RuntimeException;
+use WC_Product_CSV_Exporter;
+
+/**
+ * Drives a product CSV export through the legacy `WC_Product_CSV_Exporter` engine.
+ *
+ * @since 11.4.0
+ */
+final class ProductExporter {
+
+ /**
+ * Frees the in-memory caches between batches.
+ *
+ * @var MemoryManager
+ */
+ private MemoryManager $memory_manager;
+
+ /**
+ * Initialize the product exporter with dependencies.
+ *
+ * @internal
+ *
+ * @param MemoryManager $memory_manager Frees the in-memory caches between batches.
+ */
+ final public function init( MemoryManager $memory_manager ): void { // phpcs:ignore Generic.CodeAnalysis.UnnecessaryFinalModifier.Found -- Required by WooCommerce injection method rules
+ $this->memory_manager = $memory_manager;
+ }
+
+ /**
+ * Validate a CSV export destination.
+ *
+ * `-` (STDOUT) always passes through unchanged. Any other destination must not be a
+ * stream wrapper or URL, must not be a directory, and must have a writable parent directory.
+ *
+ * @param string $destination Path to write the CSV to, or `-` for STDOUT.
+ *
+ * @return string The destination, unchanged.
+ *
+ * @throws InvalidArgumentException When the destination is invalid.
+ */
+ public function validate_destination( string $destination ): string {
+ if ( '-' === $destination ) {
+ return $destination;
+ }
+
+ if ( preg_match( '/^[a-z][a-z0-9+.-]*:\/\//i', $destination ) ) {
+ throw new InvalidArgumentException( 'The destination cannot be a URL or stream wrapper.' );
+ }
+
+ if ( is_dir( $destination ) ) {
+ throw new InvalidArgumentException( esc_html( sprintf( 'The destination "%s" is a directory. Pass a file path instead.', $destination ) ) );
+ }
+
+ if ( file_exists( $destination ) && ! is_writable( $destination ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- CLI local filesystem check, no WP_Filesystem context here.
+ throw new InvalidArgumentException( esc_html( sprintf( 'The file "%s" is not writable.', $destination ) ) );
+ }
+
+ $directory = dirname( $destination );
+
+ if ( ! is_dir( $directory ) ) {
+ throw new InvalidArgumentException( esc_html( sprintf( 'The directory "%s" does not exist.', $directory ) ) );
+ }
+
+ if ( ! is_writable( $directory ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- CLI local filesystem check, no WP_Filesystem context here.
+ throw new InvalidArgumentException( esc_html( sprintf( 'The directory "%s" is not writable.', $directory ) ) );
+ }
+
+ return $destination;
+ }
+
+ /**
+ * Return the exportable columns as key => label.
+ *
+ * Uses `get_column_names()`, so columns added through `woocommerce_product_export_column_names`
+ * are listed and selectable, matching what an unfiltered export writes.
+ *
+ * `downloads` and `attributes` are not part of `get_default_column_names()` because they
+ * expand into numbered columns (`downloads:url1`, `attributes:value1`, ...) as products are
+ * read. `WC_CSV_Exporter::is_column_exporting()` matches them by their prefix, so they are
+ * selectable even though no column carries the bare key. The admin export form adds them the
+ * same way.
+ *
+ * @return array<string, string>
+ */
+ public function get_available_columns(): array {
+ $this->load_exporter();
+
+ return array_merge(
+ ( new WC_Product_CSV_Exporter() )->get_column_names(),
+ array(
+ 'downloads' => __( 'Downloads', 'woocommerce' ),
+ 'attributes' => __( 'Attributes', 'woocommerce' ),
+ )
+ );
+ }
+
+ /**
+ * Run a product CSV export to completion, one batch at a time.
+ *
+ * @param string $destination Path to write the CSV to, or `-` for STDOUT.
+ * @param array $options Options: columns, types, category, ids, meta, limit.
+ * @param callable|null $on_batch Optional callback invoked as `$on_batch( int $page, int $total_exported )` after each batch.
+ *
+ * @return array{exported: int, destination: string}
+ *
+ * @throws InvalidArgumentException When the temporary directory is inside the web root.
+ * @throws RuntimeException When a batch or the destination cannot be fully written.
+ */
+ public function run( string $destination, array $options, ?callable $on_batch = null ): array {
+ $this->load_exporter();
+
+ $exporter = $this->build_exporter( $options );
+ $file_path = $exporter->get_file_path();
+
+ if ( TempDirectoryGuard::is_inside_web_root( dirname( $file_path ) ) ) {
+ throw new InvalidArgumentException( 'The temporary directory resolves inside the web root. Set WP_TEMP_DIR to a location outside it.' );
+ }
+
+ $cache_addition_suspended = wp_suspend_cache_addition();
+ wp_suspend_cache_addition( true );
+
+ try {
+ $page = 1;
+
+ do {
+ $exporter->set_page( $page );
+
+ if ( ! $exporter->generate_file() ) {
+ throw new RuntimeException( esc_html( sprintf( 'Could not write export batch %d to the temporary file.', $page ) ) );
+ }
+
+ if ( null !== $on_batch ) {
+ $on_batch( $page, $exporter->get_total_exported() );
+ }
+
+ $this->memory_manager->flush_caches();
+ ++$page;
+ } while ( $exporter->get_percent_complete() < 100 );
+
+ $this->write_output( $destination, $exporter );
+ } finally {
+ wp_suspend_cache_addition( $cache_addition_suspended );
+
+ wp_delete_file( $file_path );
+ wp_delete_file( $file_path . '.headers' );
+ }
+
+ return array(
+ 'exported' => $exporter->get_total_exported(),
+ 'destination' => $destination,
+ );
+ }
+
+ /**
+ * Stream the finished export to its destination, so a large catalog is never held in memory.
+ *
+ * @param string $destination Path to write the CSV to, or `-` for STDOUT.
+ * @param CsvExporter $exporter The exporter holding the finished temporary files.
+ *
+ * @throws RuntimeException When the destination cannot be fully written.
+ */
+ private function write_output( string $destination, CsvExporter $exporter ): void {
+ $file_path = $exporter->get_file_path();
+ $header = $exporter->get_headers_row_file();
+
+ // The exporter's own writes leave a stale size in PHP's stat cache.
+ clearstatcache( true, $file_path );
+
+ // phpcs:disable WordPress.WP.AlternativeFunctions -- CLI streams to an operator-provided local path, not the uploads directory WP_Filesystem targets.
+ $source = fopen( $file_path, 'rb' );
+ $output = fopen( '-' === $destination ? 'php://output' : $destination, 'wb' );
+
+ $complete = false !== $source && false !== $output
+ && strlen( $header ) === fwrite( $output, $header )
+ && filesize( $file_path ) === stream_copy_to_stream( $source, $output );
+
+ if ( false !== $source ) {
+ fclose( $source );
+ }
+
+ if ( false !== $output ) {
+ fclose( $output );
+ }
+ // phpcs:enable WordPress.WP.AlternativeFunctions
+
+ if ( ! $complete ) {
+ throw new RuntimeException( esc_html( sprintf( 'Could not write the export to %s.', $destination ) ) );
+ }
+ }
+
+ /**
+ * Build and configure a `CsvExporter`, applying only the non-empty options.
+ *
+ * @param array $options Options: columns, types, category, ids, meta, limit.
+ *
+ * @return CsvExporter
+ */
+ private function build_exporter( array $options ): CsvExporter {
+ $exporter = new CsvExporter();
+
+ $exporter->set_filename( 'wc-product-export-' . wp_generate_password( 8, false ) . '.csv' );
+
+ if ( ! empty( $options['columns'] ) ) {
+ $exporter->set_columns_to_export( (array) $options['columns'] );
+ }
+
+ if ( ! empty( $options['types'] ) ) {
+ $exporter->set_product_types_to_export( (array) $options['types'] );
+ }
+
+ if ( ! empty( $options['category'] ) ) {
+ $exporter->set_product_category_to_export( (array) $options['category'] );
+ }
+
+ if ( ! empty( $options['ids'] ) ) {
+ $exporter->set_product_ids_to_export( (array) $options['ids'] );
+ }
+
+ if ( ! empty( $options['meta'] ) ) {
+ $exporter->enable_meta_export( true );
+ }
+
+ if ( ! empty( $options['limit'] ) ) {
+ $exporter->set_limit( (int) $options['limit'] );
+ }
+
+ return $exporter;
+ }
+
+ /**
+ * Load the admin-only exporter class, which is not included outside admin requests.
+ */
+ private function load_exporter(): void {
+ if ( ! class_exists( 'WC_Product_CSV_Exporter' ) ) {
+ include_once WC_ABSPATH . 'includes/export/class-wc-product-csv-exporter.php';
+ }
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Admin/ImportExport/TempDirectoryGuard.php b/plugins/woocommerce/src/Internal/Admin/ImportExport/TempDirectoryGuard.php
new file mode 100644
index 00000000000..a1529c38485
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Admin/ImportExport/TempDirectoryGuard.php
@@ -0,0 +1,47 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Admin\ImportExport;
+
+/**
+ * Checks where import and export scratch files would be written.
+ *
+ * `WP_TEMP_DIR`, or the `WP_CONTENT_DIR` fallback in `get_temp_dir()`, can point at a publicly served path.
+ *
+ * @since 11.4.0
+ */
+final class TempDirectoryGuard {
+
+ /**
+ * Check whether a directory resolves inside the WordPress install.
+ *
+ * @param string $directory The directory to check.
+ *
+ * @return bool True when the directory is inside `ABSPATH` or `WP_CONTENT_DIR`.
+ */
+ public static function is_inside_web_root( string $directory ): bool {
+ $directory = self::resolve( $directory );
+
+ foreach ( array( WP_CONTENT_DIR, ABSPATH ) as $root ) {
+ if ( 0 === strpos( $directory, self::resolve( $root ) ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Normalize a directory path, following symlinks when the path exists.
+ *
+ * @param string $directory The directory path.
+ *
+ * @return string The path with a trailing slash.
+ */
+ private static function resolve( string $directory ): string {
+ $resolved = realpath( $directory );
+
+ return trailingslashit( wp_normalize_path( false !== $resolved ? $resolved : $directory ) );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/ExportCommand.php b/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/ExportCommand.php
new file mode 100644
index 00000000000..f7c08dc9929
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/ExportCommand.php
@@ -0,0 +1,297 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\CLI\ImportExport\Product;
+
+use Automattic\WooCommerce\Internal\Admin\ImportExport\Product\ProductExporter;
+use InvalidArgumentException;
+use RuntimeException;
+use WC_Admin_Exporters;
+use WP_CLI;
+
+/**
+ * The `wp wc product export` command.
+ *
+ * @since 11.4.0
+ */
+final class ExportCommand {
+
+ /**
+ * Default for `--batch-size`.
+ */
+ private const DEFAULT_BATCH_SIZE = 50;
+
+ /**
+ * The product exporter.
+ *
+ * @var ProductExporter
+ */
+ private ProductExporter $exporter;
+
+ /**
+ * Initialize the command with its dependencies.
+ *
+ * @internal
+ *
+ * @param ProductExporter $exporter The product exporter.
+ */
+ final public function init( ProductExporter $exporter ): void { // phpcs:ignore Generic.CodeAnalysis.UnnecessaryFinalModifier.Found -- Required by WooCommerce injection method rules
+ $this->exporter = $exporter;
+ }
+
+ /**
+ * Export products to a CSV file.
+ *
+ * ## OPTIONS
+ *
+ * [<file>]
+ * : Path to write the CSV to, or `-` for STDOUT. Required unless `--list-columns` is used.
+ *
+ * [--columns=<list>]
+ * : Comma-separated column keys to export. Defaults to all. Use `--list-columns` to see keys.
+ * `downloads` and `attributes` each select the whole numbered group of columns.
+ *
+ * [--types=<list>]
+ * : Comma-separated product types. Defaults to all. The available types are the registered
+ * product types plus `variation`, as filtered by `woocommerce_exporter_product_types`.
+ *
+ * [--category=<list>]
+ * : Comma-separated product category slugs.
+ *
+ * [--ids=<list>]
+ * : Comma-separated product IDs. Takes priority over `--types` and `--category`, which are
+ * ignored. A variable product's variations are included.
+ *
+ * [--meta]
+ * : Include custom meta columns.
+ *
+ * [--batch-size=<n>]
+ * : Products per batch.
+ * ---
+ * default: 50
+ * ---
+ *
+ * [--list-columns]
+ * : Print available column keys and labels, then exit.
+ *
+ * [--porcelain]
+ * : Print only the number of exported products. Cannot be used with `-`.
+ *
+ * ## EXAMPLES
+ *
+ * # List the available column keys.
+ * wp wc product export --list-columns
+ *
+ * # Export every simple product to a file.
+ * wp wc product export products.csv --types=simple
+ *
+ * # Export a specific set of products and columns, including meta.
+ * wp wc product export products.csv --ids=12,34,56 --columns=id,sku,name --meta
+ *
+ * # Export to STDOUT and pipe it elsewhere.
+ * wp wc product export - --types=simple | gzip > products.csv.gz
+ *
+ * @param array $args The positional arguments.
+ * @param array $assoc_args The associative arguments.
+ */
+ public function __invoke( array $args, array $assoc_args ): void {
+ if ( (bool) WP_CLI\Utils\get_flag_value( $assoc_args, 'list-columns', false ) ) {
+ $this->list_columns();
+ return;
+ }
+
+ if ( empty( $args[0] ) ) {
+ WP_CLI::error( 'Please specify a destination file, or `-` for STDOUT.' );
+ return;
+ }
+
+ $batch_size = (int) WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', self::DEFAULT_BATCH_SIZE );
+
+ if ( $batch_size < 1 ) {
+ WP_CLI::error( 'The --batch-size argument must be a positive integer.' );
+ return;
+ }
+
+ $destination = (string) $args[0];
+ $columns = $this->parse_list( (string) WP_CLI\Utils\get_flag_value( $assoc_args, 'columns', '' ) );
+ $types = $this->parse_list( (string) WP_CLI\Utils\get_flag_value( $assoc_args, 'types', '' ) );
+ $category = $this->parse_list( (string) WP_CLI\Utils\get_flag_value( $assoc_args, 'category', '' ) );
+ $ids = $this->parse_list( (string) WP_CLI\Utils\get_flag_value( $assoc_args, 'ids', '' ) );
+ $meta = (bool) WP_CLI\Utils\get_flag_value( $assoc_args, 'meta', false );
+ $porcelain = (bool) WP_CLI\Utils\get_flag_value( $assoc_args, 'porcelain', false );
+
+ if ( '-' === $destination && $porcelain ) {
+ WP_CLI::error( 'The --porcelain flag cannot be used with `-`, because STDOUT carries the CSV.' );
+ return;
+ }
+
+ // A filter that ends up empty would export the whole catalog, so a passed flag must yield values.
+ $filters = array(
+ 'types' => $types,
+ 'category' => $category,
+ );
+
+ foreach ( $filters as $flag => $values ) {
+ if ( isset( $assoc_args[ $flag ] ) && empty( $values ) ) {
+ WP_CLI::error( sprintf( 'The --%s argument requires at least one value.', $flag ) );
+ }
+ }
+
+ $this->validate_columns( $columns );
+ $this->validate_types( $types );
+ $ids = $this->validate_ids( $ids, isset( $assoc_args['ids'] ) );
+
+ try {
+ $destination = $this->exporter->validate_destination( $destination );
+
+ $results = $this->exporter->run(
+ $destination,
+ array(
+ 'columns' => $columns,
+ 'types' => $types,
+ 'category' => $category,
+ 'ids' => $ids,
+ 'meta' => $meta,
+ 'limit' => $batch_size,
+ ),
+ function ( int $page, int $total_exported ) use ( $destination, $porcelain ) {
+ if ( '-' !== $destination && ! $porcelain ) {
+ WP_CLI::log( sprintf( 'Batch %d: %d products exported so far.', $page, $total_exported ) );
+ }
+ }
+ );
+ } catch ( InvalidArgumentException | RuntimeException $e ) {
+ // Engine exceptions are HTML-escaped for any output context; this one is a terminal.
+ WP_CLI::error( wp_specialchars_decode( $e->getMessage(), ENT_QUOTES ) );
+ return;
+ }
+
+ $this->report_results( $results, $porcelain );
+ }
+
+ /**
+ * Print available column keys and labels.
+ */
+ private function list_columns(): void {
+ $rows = array();
+
+ foreach ( $this->exporter->get_available_columns() as $key => $label ) {
+ $rows[] = array(
+ 'key' => $key,
+ 'label' => $label,
+ );
+ }
+
+ WP_CLI\Utils\format_items( 'table', $rows, array( 'key', 'label' ) );
+ }
+
+ /**
+ * Print the final export result.
+ *
+ * @param array $results The `ProductExporter::run()` result.
+ * @param bool $porcelain Whether to print only the exported count.
+ */
+ private function report_results( array $results, bool $porcelain ): void {
+ if ( '-' === $results['destination'] ) {
+ return;
+ }
+
+ if ( $porcelain ) {
+ // `line()`, not `log()`, so `--quiet` cannot hide the output a script reads.
+ WP_CLI::line( (string) $results['exported'] );
+ return;
+ }
+
+ WP_CLI::success( sprintf( 'Exported %d products to %s.', $results['exported'], $results['destination'] ) );
+ }
+
+ /**
+ * Split a comma-separated CLI argument into a trimmed, non-empty list.
+ *
+ * @param string $value The raw comma-separated value.
+ *
+ * @return string[]
+ */
+ private function parse_list( string $value ): array {
+ if ( '' === $value ) {
+ return array();
+ }
+
+ return array_values(
+ array_filter(
+ array_map( 'trim', explode( ',', $value ) ),
+ static fn( string $item ): bool => '' !== $item
+ )
+ );
+ }
+
+ /**
+ * Validate `--columns` against the exporter's known column keys.
+ *
+ * @param string[] $columns Requested column keys.
+ */
+ private function validate_columns( array $columns ): void {
+ if ( empty( $columns ) ) {
+ return;
+ }
+
+ $available = array_keys( $this->exporter->get_available_columns() );
+ $unknown = array_diff( $columns, $available );
+
+ if ( ! empty( $unknown ) ) {
+ WP_CLI::error( sprintf( 'Unknown column key(s): %s. Use --list-columns to see the available keys.', implode( ', ', $unknown ) ) );
+ }
+ }
+
+ /**
+ * Validate `--types` against the product types the admin exporter supports.
+ *
+ * Goes through `WC_Admin_Exporters::get_product_types()` rather than `wc_get_product_types()`
+ * so the `woocommerce_exporter_product_types` filter decides what is exportable here too, the
+ * same list `WC_Product_CSV_Exporter` seeds itself with.
+ *
+ * @param string[] $types Requested product types.
+ */
+ private function validate_types( array $types ): void {
+ if ( empty( $types ) ) {
+ return;
+ }
+
+ $available = array_keys( WC_Admin_Exporters::get_product_types() );
+ $unknown = array_diff( $types, $available );
+
+ if ( ! empty( $unknown ) ) {
+ WP_CLI::error( sprintf( 'Unknown product type(s): %s.', implode( ', ', $unknown ) ) );
+ }
+ }
+
+ /**
+ * Validate `--ids` as positive integers and cast them.
+ *
+ * A filter that ends up empty would export the whole catalog, so a passed flag must yield IDs.
+ *
+ * @param string[] $ids Requested product IDs.
+ * @param bool $provided Whether `--ids` was passed.
+ *
+ * @return int[]
+ */
+ private function validate_ids( array $ids, bool $provided ): array {
+ if ( $provided && empty( $ids ) ) {
+ WP_CLI::error( 'The --ids argument requires at least one product ID.' );
+ }
+
+ $invalid = array_filter(
+ $ids,
+ static function ( string $id ): bool {
+ return ! ctype_digit( $id ) || (int) $id < 1;
+ }
+ );
+
+ if ( ! empty( $invalid ) ) {
+ WP_CLI::error( sprintf( 'Invalid product ID(s): %s.', implode( ', ', $invalid ) ) );
+ }
+
+ return array_map( 'intval', $ids );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/Runner.php b/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/Runner.php
new file mode 100644
index 00000000000..7e8055c98d3
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/CLI/ImportExport/Product/Runner.php
@@ -0,0 +1,48 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\CLI\ImportExport\Product;
+
+use WP_CLI;
+
+/**
+ * Registers the `wp wc product export` WP-CLI command.
+ *
+ * @since 11.4.0
+ */
+final class Runner {
+
+ /**
+ * The export command.
+ *
+ * @var ExportCommand
+ */
+ private ExportCommand $export_command;
+
+ /**
+ * Initialize the runner with dependencies.
+ *
+ * @internal
+ *
+ * @param ExportCommand $export_command The export command.
+ */
+ final public function init( ExportCommand $export_command ): void { // phpcs:ignore Generic.CodeAnalysis.UnnecessaryFinalModifier.Found -- Required by WooCommerce injection method rules
+ $this->export_command = $export_command;
+ }
+
+ /**
+ * Register the product CSV commands with WP-CLI.
+ */
+ public function register_commands(): void {
+ if ( ! class_exists( 'WP_CLI' ) ) {
+ return;
+ }
+
+ WP_CLI::add_command(
+ 'wc product export',
+ $this->export_command,
+ array( 'shortdesc' => 'Export products to a CSV file.' )
+ );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/Product/ProductExporterTest.php b/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/Product/ProductExporterTest.php
new file mode 100644
index 00000000000..f026b9ed000
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/Product/ProductExporterTest.php
@@ -0,0 +1,385 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Admin\ImportExport\Product;
+
+use Automattic\WooCommerce\Internal\Admin\ImportExport\Product\ProductExporter;
+use WC_Helper_Product;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the ProductExporter class.
+ */
+class ProductExporterTest extends WC_Unit_Test_Case {
+
+ /**
+ * The System Under Test.
+ *
+ * @var ProductExporter
+ */
+ private $sut;
+
+ /**
+ * Files created by tests that should be deleted during tear down.
+ *
+ * @var string[]
+ */
+ private $files_to_delete = array();
+
+ /**
+ * Set up test fixtures.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->sut = wc_get_container()->get( ProductExporter::class );
+ }
+
+ /**
+ * Tear down test fixtures.
+ */
+ public function tearDown(): void {
+ try {
+ foreach ( $this->files_to_delete as $file ) {
+ wp_delete_file( $file );
+ }
+ $this->files_to_delete = array();
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * @testdox Should export created products to a CSV file with an ID and SKU header.
+ */
+ public function test_run_exports_products_to_a_file(): void {
+ WC_Helper_Product::create_simple_product();
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+
+ $results = $this->sut->run( $destination, array() );
+
+ $this->assertSame( 2, $results['exported'] );
+ $lines = $this->read_csv_lines( $destination );
+ $this->assertStringContainsString( 'ID', $lines[0] );
+ $this->assertStringContainsString( 'SKU', $lines[0] );
+ $this->assertCount( 3, $lines, 'Expected a header row plus one row per exported product' );
+ }
+
+ /**
+ * @testdox Should restrict the export to the given product IDs.
+ */
+ public function test_run_restricts_export_to_given_ids(): void {
+ WC_Helper_Product::create_simple_product();
+ $target = WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+
+ $results = $this->sut->run( $destination, array( 'ids' => array( $target->get_id() ) ) );
+
+ $this->assertSame( 1, $results['exported'] );
+ $lines = $this->read_csv_lines( $destination );
+ $this->assertCount( 2, $lines, 'Expected a header row plus the single requested product' );
+ $this->assertStringContainsString( (string) $target->get_id(), $lines[1] );
+ }
+
+ /**
+ * @testdox Should restrict the exported header to the given columns.
+ */
+ public function test_run_restricts_columns(): void {
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+
+ $this->sut->run( $destination, array( 'columns' => array( 'id', 'sku' ) ) );
+
+ $lines = $this->read_csv_lines( $destination );
+ $header = str_getcsv( $lines[0] );
+ $this->assertSame( array( 'ID', 'SKU' ), $header );
+ }
+
+ /**
+ * @testdox Should offer the grouped `downloads` and `attributes` keys alongside the default columns.
+ */
+ public function test_get_available_columns_includes_the_grouped_special_columns(): void {
+ $columns = $this->sut->get_available_columns();
+
+ $this->assertArrayHasKey( 'id', $columns );
+ $this->assertArrayHasKey( 'downloads', $columns );
+ $this->assertArrayHasKey( 'attributes', $columns );
+ }
+
+ /**
+ * @testdox Should offer columns added through the `woocommerce_product_export_column_names` filter.
+ */
+ public function test_get_available_columns_includes_filtered_column_names(): void {
+ $add_column = static function ( array $columns ): array {
+ $columns['custom_column'] = 'Custom column';
+ return $columns;
+ };
+ add_filter( 'woocommerce_product_export_column_names', $add_column );
+
+ try {
+ $columns = $this->sut->get_available_columns();
+ } finally {
+ remove_filter( 'woocommerce_product_export_column_names', $add_column );
+ }
+
+ $this->assertSame( 'Custom column', $columns['custom_column'] ?? null );
+ }
+
+ /**
+ * @testdox Should export the numbered attribute columns when `attributes` is the only selected column.
+ */
+ public function test_run_exports_the_attribute_group_when_selected_as_a_column(): void {
+ WC_Helper_Product::create_variation_product();
+
+ $destination = $this->new_temp_path();
+
+ $this->sut->run( $destination, array( 'columns' => array( 'attributes' ) ) );
+
+ $lines = $this->read_csv_lines( $destination );
+ $header = str_getcsv( $lines[0] );
+
+ $this->assertContains( 'Attribute 1 name', $header );
+ }
+
+ /**
+ * @testdox Should print the header and rows and leave no file when the destination is `-`.
+ */
+ public function test_run_prints_csv_for_stdout_destination(): void {
+ $product = WC_Helper_Product::create_simple_product();
+
+ $before_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+
+ ob_start();
+ try {
+ $this->sut->run( '-', array() );
+ } finally {
+ $output = (string) ob_get_clean();
+ }
+
+ $this->assertStringContainsString( 'ID', $output );
+ $this->assertStringContainsString( $product->get_sku(), $output );
+
+ $after_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+ $this->assertSame( $before_listing, $after_listing, 'No temp export file should remain on disk' );
+ }
+
+ /**
+ * @testdox Should delete the temporary files once the export completes.
+ */
+ public function test_run_cleans_up_temp_files(): void {
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+ $before_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+
+ $this->sut->run( $destination, array() );
+
+ $after_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+ $this->assertSame( $before_listing, $after_listing, 'Temporary export files should be removed from the temp directory' );
+ }
+
+ /**
+ * @testdox Should write the temporary export file under get_temp_dir(), not the uploads directory.
+ */
+ public function test_run_writes_temp_file_under_temp_dir_not_uploads(): void {
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+ $upload_dir = wp_upload_dir();
+ $seen_temp_files = null;
+
+ $this->sut->run(
+ $destination,
+ array(),
+ function () use ( &$seen_temp_files ) {
+ $seen_temp_files = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*.csv' );
+ }
+ );
+
+ $this->assertNotEmpty( $seen_temp_files, 'Expected the export temp file to exist under get_temp_dir() during the run' );
+
+ $upload_matches = glob( trailingslashit( $upload_dir['basedir'] ) . 'wc-product-export-*' );
+ $this->assertSame( array(), $upload_matches, 'No export temp file should be written to the uploads directory' );
+ }
+
+ /**
+ * @testdox Should delete the temp CSV and headers files even when a batch throws.
+ */
+ public function test_run_cleans_up_temp_files_when_a_batch_throws(): void {
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+ $before_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+ $callback = function () {
+ throw new \RuntimeException( 'Simulated failure mid-batch.' );
+ };
+
+ add_filter( 'woocommerce_product_export_row_data', $callback );
+
+ try {
+ $this->sut->run( $destination, array() );
+ $this->fail( 'Expected a RuntimeException to be thrown mid-batch.' );
+ } catch ( \RuntimeException $exception ) {
+ $this->assertSame( 'Simulated failure mid-batch.', $exception->getMessage() );
+ } finally {
+ remove_filter( 'woocommerce_product_export_row_data', $callback );
+ }
+
+ $after_listing = glob( trailingslashit( get_temp_dir() ) . 'wc-product-export-*' );
+ $this->assertSame( $before_listing, $after_listing, 'Temporary export files should be removed even when a batch throws' );
+ }
+
+ /**
+ * @testdox Should leave cache addition suspended when it was suspended before the export.
+ */
+ public function test_run_restores_the_previous_cache_addition_state(): void {
+ WC_Helper_Product::create_simple_product();
+
+ wp_suspend_cache_addition( true );
+
+ try {
+ $this->sut->run( $this->new_temp_path(), array() );
+ $this->assertTrue( wp_suspend_cache_addition() );
+ } finally {
+ wp_suspend_cache_addition( false );
+ }
+ }
+
+ /**
+ * @testdox Should export every product exactly once when the export spans several batches.
+ */
+ public function test_run_exports_all_products_across_batches(): void {
+ for ( $i = 0; $i < 5; $i++ ) {
+ WC_Helper_Product::create_simple_product();
+ }
+
+ $destination = $this->new_temp_path();
+
+ $results = $this->sut->run( $destination, array( 'limit' => 2 ) );
+
+ $rows = $this->read_csv_rows( $destination );
+ $ids = array_column( $rows, 0 );
+ $this->assertSame( 5, $results['exported'] );
+ $this->assertCount( 5, $rows, 'Expected one data row per product' );
+ $this->assertCount( 5, array_unique( $ids ), 'No product should be exported twice' );
+ }
+
+ /**
+ * @testdox Should export and count the variations of a variable product when the export spans several batches.
+ */
+ public function test_run_counts_variations_across_batches(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $simple = WC_Helper_Product::create_simple_product();
+ $variations = count( $variable->get_children() );
+
+ $destination = $this->new_temp_path();
+
+ $results = $this->sut->run(
+ $destination,
+ array(
+ 'ids' => array( $variable->get_id(), $simple->get_id() ),
+ 'limit' => 1,
+ )
+ );
+
+ $this->assertGreaterThan( 0, $variations );
+ $this->assertSame( 2 + $variations, $results['exported'] );
+ $this->assertCount( 2 + $variations, $this->read_csv_rows( $destination ) );
+ }
+
+ /**
+ * @testdox Should keep attribute columns in the header and align later rows when only an early batch has attributes.
+ */
+ public function test_run_keeps_columns_aligned_when_attributes_only_on_early_batch(): void {
+ WC_Helper_Product::create_variation_product();
+ WC_Helper_Product::create_simple_product();
+ WC_Helper_Product::create_simple_product();
+
+ $destination = $this->new_temp_path();
+
+ $this->sut->run( $destination, array( 'limit' => 1 ) );
+
+ $lines = $this->read_csv_lines( $destination );
+ $header = str_getcsv( $lines[0] );
+ $this->assertContains( 'Attribute 1 name', $header );
+
+ foreach ( array_slice( $lines, 1 ) as $line ) {
+ $this->assertCount( count( $header ), str_getcsv( $line ), 'Every row should have one value per header column' );
+ }
+ }
+
+ /**
+ * @testdox Should reject a URL, a stream wrapper, and a path in a non-existent directory.
+ * @testWith ["http://example.com/out.csv"]
+ * ["php://memory"]
+ * ["/path/does/not/exist/out.csv"]
+ *
+ * @param string $destination The invalid destination under test.
+ */
+ public function test_validate_destination_rejects_invalid_destinations( string $destination ): void {
+ $this->expectException( \InvalidArgumentException::class );
+
+ $this->sut->validate_destination( $destination );
+ }
+
+ /**
+ * @testdox Should reject a directory before exporting anything.
+ */
+ public function test_validate_destination_rejects_a_directory(): void {
+ $this->expectException( \InvalidArgumentException::class );
+ $this->expectExceptionMessage( 'is a directory' );
+
+ $this->sut->validate_destination( get_temp_dir() );
+ }
+
+ /**
+ * @testdox Should pass a valid local path and STDOUT marker through unchanged.
+ */
+ public function test_validate_destination_accepts_valid_destinations(): void {
+ $path = $this->new_temp_path();
+
+ $this->assertSame( $path, $this->sut->validate_destination( $path ) );
+ $this->assertSame( '-', $this->sut->validate_destination( '-' ) );
+ }
+
+ /**
+ * Reserve a writable temporary file path and mark it for clean up.
+ *
+ * @return string
+ */
+ private function new_temp_path(): string {
+ $path = wp_tempnam( 'wc-product-exporter-test' );
+ $this->files_to_delete[] = $path;
+
+ return $path;
+ }
+
+ /**
+ * Read a written CSV file and return its data rows, without the header.
+ *
+ * @param string $path Path to the CSV file.
+ *
+ * @return array[]
+ */
+ private function read_csv_rows( string $path ): array {
+ return array_map( 'str_getcsv', array_slice( $this->read_csv_lines( $path ), 1 ) );
+ }
+
+ /**
+ * Read a written CSV file and split it into non-empty lines.
+ *
+ * @param string $path Path to the CSV file.
+ *
+ * @return string[]
+ */
+ private function read_csv_lines( string $path ): array {
+ // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading a local test fixture file.
+ $content = file_get_contents( $path );
+ $content = str_replace( chr( 239 ) . chr( 187 ) . chr( 191 ), '', $content );
+
+ return array_values( array_filter( preg_split( "/\r\n|\n|\r/", $content ) ) );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/TempDirectoryGuardTest.php b/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/TempDirectoryGuardTest.php
new file mode 100644
index 00000000000..81a08f80ee3
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Admin/ImportExport/TempDirectoryGuardTest.php
@@ -0,0 +1,50 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Admin\ImportExport;
+
+use Automattic\WooCommerce\Internal\Admin\ImportExport\TempDirectoryGuard;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the TempDirectoryGuard class.
+ */
+class TempDirectoryGuardTest extends WC_Unit_Test_Case {
+
+ /**
+ * @testdox Should treat the WordPress install and directories inside it as the web root.
+ */
+ public function test_is_inside_web_root_for_install_directories(): void {
+ $this->assertTrue( TempDirectoryGuard::is_inside_web_root( ABSPATH ), 'ABSPATH should be inside the web root' );
+ $this->assertTrue( TempDirectoryGuard::is_inside_web_root( WP_CONTENT_DIR ), 'WP_CONTENT_DIR should be inside the web root' );
+ $this->assertTrue( TempDirectoryGuard::is_inside_web_root( WP_CONTENT_DIR . '/not-created-yet' ), 'A missing directory under WP_CONTENT_DIR should be inside the web root' );
+ }
+
+ /**
+ * @testdox Should not match a directory that only shares a name prefix with the install.
+ */
+ public function test_is_inside_web_root_ignores_a_sibling_with_the_same_prefix(): void {
+ $this->assertFalse( TempDirectoryGuard::is_inside_web_root( untrailingslashit( ABSPATH ) . '-sibling' ) );
+ }
+
+ /**
+ * @testdox Should follow a symlink that points into the web root.
+ */
+ public function test_is_inside_web_root_follows_symlinks(): void {
+ $link = sys_get_temp_dir() . '/wc-temp-guard-link-' . wp_generate_password( 8, false );
+ symlink( WP_CONTENT_DIR, $link );
+
+ $result = TempDirectoryGuard::is_inside_web_root( $link );
+
+ unlink( $link ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- removing a symlink created by this test.
+
+ $this->assertTrue( $result, 'A symlink to WP_CONTENT_DIR should be inside the web root' );
+ }
+
+ /**
+ * @testdox Should accept the system temp directory.
+ */
+ public function test_is_inside_web_root_is_false_for_the_system_temp_directory(): void {
+ $this->assertFalse( TempDirectoryGuard::is_inside_web_root( sys_get_temp_dir() ) );
+ }
+}