Files
WP-Content-Sync/src/Admin/FileImportController.php
T
2026-05-01 15:23:25 -05:00

110 lines
2.9 KiB
PHP

<?php
/**
* Admin file import controller.
*
* @package WPContentSync
*/
namespace WPContentSync\Admin;
use WPContentSync\Logging\LoggerInterface;
use WPContentSync\Sync\SyncEngine;
use WPContentSync\Transport\FileTransportInterface;
final class FileImportController {
private FileTransportInterface $transport;
private LoggerInterface $logger;
private SyncEngine $sync_engine;
public function __construct( FileTransportInterface $transport, LoggerInterface $logger, SyncEngine $sync_engine ) {
$this->transport = $transport;
$this->logger = $logger;
$this->sync_engine = $sync_engine;
}
public function register(): void {
add_action( 'admin_post_wpcs_import_package', array( $this, 'handleImport' ) );
}
public function handleImport(): void {
if ( ! current_user_can( 'manage_options' ) ) {
throw new \RuntimeException( 'You do not have permission to import content packages.' );
}
if ( ! check_admin_referer( 'wpcs_import_package', 'wpcs_import_package_nonce' ) ) {
throw new \RuntimeException( 'The import request could not be verified.' );
}
if ( ! isset( $_FILES['wpcs_package_file']['tmp_name'], $_FILES['wpcs_package_file']['error'] ) ) {
throw new \RuntimeException( 'Choose a package JSON file before importing.' );
}
if ( UPLOAD_ERR_OK !== (int) $_FILES['wpcs_package_file']['error'] ) {
throw new \RuntimeException( 'The package file could not be uploaded.' );
}
$uploaded_file = sanitize_text_field( (string) $_FILES['wpcs_package_file']['tmp_name'] );
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a validated local upload temp file.
$contents = file_get_contents( $uploaded_file );
if ( false === $contents ) {
throw new \RuntimeException( 'The package file could not be read.' );
}
try {
$package = $this->transport->import( $contents );
} catch ( \InvalidArgumentException $exception ) {
$this->logger->warning(
'Rejected imported content package.',
array(
'error' => $exception->getMessage(),
)
);
$this->redirectToDashboard(
array(
'wpcs_import_error' => $exception->getMessage(),
)
);
return;
}
$result = $this->sync_engine->importPackage( $package );
if ( ! $result->isSuccessful() ) {
$this->logger->error(
'Imported content package failed.',
$result->toArray()
);
$this->redirectToDashboard(
array(
'wpcs_import_error' => implode( ' ', $result->errors() ),
)
);
return;
}
$this->logger->info( 'Imported content package.', $result->toArray() );
$this->redirectToDashboard(
array(
'wpcs_imported' => '1',
)
);
}
/**
* @param array<string, string> $args Redirect query args.
*/
private function redirectToDashboard( array $args ): void {
wp_safe_redirect(
add_query_arg(
$args,
admin_url( 'admin.php?page=wp-content-sync' )
)
);
}
}