Google_Sheet_Helpers::maybe_migrate_googlesheets()

Changes the COLUMN_NAME and COLUMN_VALUE to GS_COLUMN_NAME and GS_COLUMN_VALUE in the postmeta.


Return Return

(void)


Source Source

File: src/integrations/google-sheet/helpers/google-sheet-helpers.php

	public function maybe_migrate_googlesheets() {

		if ( 'yes' === get_option( 'uncanny_automator_google_sheets_migrated' ) ) {
			return;
		}

		global $wpdb;

		// Fetch all postmeta records where key is equal to "WORKSHEET_FIELDS".
		// Only fetch meta_value that contains COLUMN_NAME and not GS_COLUMN_NAME.
		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT post_id, meta_key, meta_value
				FROM $wpdb->postmeta
				WHERE meta_key = %s
				AND meta_value LIKE %s
				AND meta_value LIKE %s
				AND meta_value NOT LIKE %s
				AND meta_value NOT LIKE %s
				",
				'WORKSHEET_FIELDS',
				'%%COLUMN_NAME%%',
				'%%COLUMN_VALUE%%',
				'%%GS_COLUMN_NAME%%',
				'%%GS_COLUMN_VALUE%%'
			),
			OBJECT
		);

		if ( ! empty( $results ) ) {

			// Get the old meta value.
			foreach ( $results as $result ) {

				// Initiate the new meta value as empty array.
				$meta_value_new = array();

				// Get the post id.
				$post_id = $result->post_id;

				// Decode the old meta value to make it array.
				$meta_values = json_decode( $result->meta_value );

				if ( ! empty( $meta_values ) ) {
					// Iterate through each old value and construct new array with new keys.
					foreach ( $meta_values as $meta_value ) {

						$new_meta = array(
							// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
							'GS_COLUMN_NAME'  => $meta_value->COLUMN_NAME,
							// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
							'GS_COLUMN_VALUE' => $meta_value->COLUMN_VALUE,
						);

						// Add other meta keys and values if exists except for COLUMN_NAME and COLUMN_VALUE.
						if ( isset( $meta_value->COLUMN_UPDATE ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
							$new_meta['COLUMN_UPDATE'] = $meta_value->COLUMN_UPDATE; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
						}

						$meta_value_new[] = $new_meta;

					}

					// Don't escape unicode characters.
					$new_meta_value = wp_json_encode( $meta_value_new, JSON_UNESCAPED_UNICODE );

					// Update the post meta with the new array containing the new keys.
					// Only update if $new_meta_value is not empty.
					if ( ! empty( $new_meta_value ) ) {
						update_post_meta( $post_id, 'WORKSHEET_FIELDS', $new_meta_value );
					}
				}
			}
		}

		// Update the option 'uncanny_automator_google_sheets_migrated'.
		update_option( 'uncanny_automator_google_sheets_migrated', 'yes', false );

	}