| 1 |
<?php |
| 2 |
/** |
| 3 |
* Our class responsible for running one-time data migrations on plugin update. |
| 4 |
* |
| 5 |
* @package ForceRefresh |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace JordanLeven\Plugins\ForceRefresh\Services; |
| 9 |
|
| 10 |
/** |
| 11 |
* Class for running plugin data migrations. |
| 12 |
*/ |
| 13 |
class Migration_Service { |
| 14 |
|
| 15 |
const OPTION_MIGRATIONS_RAN = 'force_refresh_migrations_ran'; |
| 16 |
|
| 17 |
/** |
| 18 |
* Run any migrations that have not yet been applied. |
| 19 |
* |
| 20 |
* @return void |
| 21 |
*/ |
| 22 |
public static function run_pending(): void { |
| 23 |
$ran = get_option( self::OPTION_MIGRATIONS_RAN, array() ); |
| 24 |
|
| 25 |
if ( ! is_array( $ran ) ) { |
| 26 |
$ran = array(); |
| 27 |
} |
| 28 |
|
| 29 |
$ran_before = $ran; |
| 30 |
|
| 31 |
foreach ( self::get_migrations() as $id => $migration ) { |
| 32 |
if ( ! in_array( $id, $ran, true ) ) { |
| 33 |
$migration(); |
| 34 |
$ran[] = $id; |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
if ( $ran !== $ran_before ) { |
| 39 |
update_option( self::OPTION_MIGRATIONS_RAN, $ran ); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Return the ordered list of migrations keyed by a unique ID. |
| 45 |
* |
| 46 |
* @return array<string, callable> |
| 47 |
*/ |
| 48 |
private static function get_migrations(): array { |
| 49 |
return array( |
| 50 |
'consolidate_page_versions_to_option' => array( __CLASS__, 'migrate_page_versions_to_option' ), |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Migrate per-page versions from individual post meta entries into a single option. |
| 56 |
* |
| 57 |
* Reads all posts carrying the legacy meta key, writes them into |
| 58 |
* OPTION_PAGE_VERSIONS, then removes the individual meta rows. |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
private static function migrate_page_versions_to_option(): void { |
| 63 |
global $wpdb; |
| 64 |
|
| 65 |
$legacy_key = Versions_Storage_Service::OPTION_PAGE_VERSION_LEGACY; |
| 66 |
|
| 67 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery |
| 68 |
$rows = $wpdb->get_results( |
| 69 |
$wpdb->prepare( |
| 70 |
"SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s", |
| 71 |
$legacy_key |
| 72 |
) |
| 73 |
); |
| 74 |
|
| 75 |
if ( empty( $rows ) ) { |
| 76 |
return; |
| 77 |
} |
| 78 |
|
| 79 |
$versions = array(); |
| 80 |
foreach ( $rows as $row ) { |
| 81 |
$versions[ (string) $row->post_id ] = $row->meta_value; |
| 82 |
} |
| 83 |
|
| 84 |
update_option( Versions_Storage_Service::OPTION_PAGE_VERSIONS, $versions ); |
| 85 |
|
| 86 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.SlowDBQuery.slow_db_query_meta_key |
| 87 |
$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => $legacy_key ) ); |
| 88 |
} |
| 89 |
} |
| 90 |
|