<?php
/**
 * Replaces any found host name occurrence by a placeholder.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemValueHandler\ValueProcessor;

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemValueHandler\ItemValueHandlerBase;

/**
 * Replaces any found host name occurrence by a placeholder.
 *
 * This is faster than the HostNameTransmutationHandler, but it does not handle
 * nested serialized data, e.g. JSON serialized data.
 */
class UrlHostNameProcessor extends ValueProcessorBase {
	/**
	 * {@inheritDoc}
	 */
	public static function getId(): string {
		return 'url_host_name';
	}

	/**
	 * {@inheritDoc}
	 */
	public static function getLabel(): string {
		return _dpgettext( 'deployer-core', 'processor label', 'Strip host name from URL' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function process( $value, int $operation, ?callable $progress_callback = null ) {
		if ( ! is_string( $value ) ) {
			// We only process strings here.
			return $value;
		}

		switch ( $operation ) {
			case ItemValueHandlerBase::OPERATION__EXPORT:
				// This is also the operation to use when we want to compare the values.
				return $this->replaceHostNameByPlaceholder( $value );

			case ItemValueHandlerBase::OPERATION__IMPORT__FINALIZE:
			case ItemValueHandlerBase::OPERATION__IMPORT__PRESAVE:
				return $this->replacePlaceholderByHostName( $value );
		}

		return $value;
	}

	/**
	 * Replaces the current host name occurrences by a placeholder.
	 *
	 * @param string $value The value to process.
	 *
	 * @return string The value with the host name replaced by a placeholder.
	 *
	 * @throws WpDeployException Could not replace the host name by a placeholder.
	 */
	private function replaceHostNameByPlaceholder( string $value ): string {
		$current_host_name = untrailingslashit( get_site_url() );

		return str_replace( $current_host_name, static::getProcessorPlaceholder(), $value );
	}

	/**
	 * Replaces the placeholders by the current host name.
	 *
	 * @param string $value The value to process.
	 *
	 * @return string The value with the placeholders replaced by the host name.
	 *
	 * @throws WpDeployException Could not replace the placeholders by the host name.
	 */
	private function replacePlaceholderByHostName( string $value ): string {
		$current_host_name = untrailingslashit( get_site_url() );

		return str_replace( static::getProcessorPlaceholder(), $current_host_name, $value );
	}
}
