Automattic\WooCommerce\Database\Migrations

MetaToMetaTableMigrator::classify_update_insert_records()privateWC 1.0

Classify each record on whether to migrate or update.

Method of the class: MetaToMetaTableMigrator{}

No Hooks.

Return

Array[]. Returns two arrays, first for records to migrate, and second for records to upgrade.

Usage

// private - for code of main (parent) class only
$result = $this->classify_update_insert_records( $to_migrate, $already_migrated ): array;
$to_migrate(array) (required)
Records to migrate.
$already_migrated(array) (required)
Records already migrated.

MetaToMetaTableMigrator::classify_update_insert_records() code WC 7.1.0

private function classify_update_insert_records( array $to_migrate, array $already_migrated ): array {
	$to_update = array();
	$to_insert = array();

	foreach ( $to_migrate as $entity_id => $rows ) {
		foreach ( $rows as $meta_key => $meta_values ) {
			// If there is no corresponding record in the destination table then insert.
			// If there is single value in both already migrated and current then update.
			// If there are multiple values in either already_migrated records or in to_migrate_records, then insert instead of updating.
			if ( ! isset( $already_migrated[ $entity_id ][ $meta_key ] ) ) {
				if ( ! isset( $to_insert[ $entity_id ] ) ) {
					$to_insert[ $entity_id ] = array();
				}
				$to_insert[ $entity_id ][ $meta_key ] = $meta_values;
			} else {
				if ( 1 === count( $meta_values ) && 1 === count( $already_migrated[ $entity_id ][ $meta_key ] ) ) {
					if ( $meta_values[0] === $already_migrated[ $entity_id ][ $meta_key ][0]['meta_value'] ) {
						continue;
					}
					if ( ! isset( $to_update[ $entity_id ] ) ) {
						$to_update[ $entity_id ] = array();
					}
					$to_update[ $entity_id ][ $meta_key ] = array(
						'id'         => $already_migrated[ $entity_id ][ $meta_key ][0]['id'],
						// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
						'meta_value' => $meta_values[0],
					);
					continue;
				}

				// There are multiple meta entries, let's find the unique entries and insert.
				$unique_meta_values = array_diff( $meta_values, array_column( $already_migrated[ $entity_id ][ $meta_key ], 'meta_value' ) );
				if ( 0 === count( $unique_meta_values ) ) {
					continue;
				}
				if ( ! isset( $to_insert[ $entity_id ] ) ) {
					$to_insert[ $entity_id ] = array();
				}
				$to_insert[ $entity_id ][ $meta_key ] = $unique_meta_values;
			}
		}
	}

	return array( $to_insert, $to_update );
}