<?php
/**
 * Provides the incoming and local items metadata for the diff UI.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\ItemTracker;

use EaLab\WP_Deployer\vendor\Dakwamine\Component\ComponentBasedObject;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Exception\WpDeployException;

/**
 * Provides the incoming and local items metadata for the diff UI.
 */
class MetadataForDiff extends ComponentBasedObject {
	/**
	 * Extracts the metadata information from the items.
	 *
	 * @param ItemTrackerBase     $item_tracker The item tracker.
	 * @param array<string,mixed> $local_item The local deployment item.
	 * @param array<string,mixed> $incoming_item The incoming deployment item.
	 *
	 * @return array<string,array<string,string>> The metadata information, keyed by "local_item" and "incoming_item".
	 *
	 * @throws WpDeployException Error on metadata extraction.
	 */
	public static function extractFromItems(
		ItemTrackerBase $item_tracker,
		array $local_item,
		array $incoming_item
	): array {
		$meta_table_name = $item_tracker->getTrackingMetaDataTableName( false );

		// Append the metadata values. We are doing it here because it's one of the few
		// locations where both "incoming" and "destination" values are available.
		// Extract the metadata fields. They will be appended to the result.
		$local_item_metadata_fields    = $local_item['fields'];
		$incoming_item_metadata_fields = $incoming_item['fields'];

		$local_item_metadata_fields = array_filter(
			$local_item_metadata_fields,
			function ( $field_name ) use ( $meta_table_name ) {
				return false !== strpos( $field_name, $meta_table_name . '.' );
			},
			ARRAY_FILTER_USE_KEY
		);

		$incoming_item_metadata_fields = array_filter(
			$incoming_item_metadata_fields,
			function ( $field_name ) use ( $meta_table_name ) {
				return false !== strpos( $field_name, $meta_table_name . '.' );
			},
			ARRAY_FILTER_USE_KEY
		);

		return array(
			'local_item'    => $local_item_metadata_fields,
			'incoming_item' => $incoming_item_metadata_fields,
		);
	}
}