PluginProbe
Force Refresh / 3.2.0
Force Refresh v3.2.0
3.2.1 3.2.0 3.1.2 3.1.1 3.1.0 trunk 1.0.0 1.1.0 1.1.1 1.1.2 1.2.0 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.10.0 2.10.1 2.10.2 2.11.0 2.11.1 2.12.0 All 54 releases
force-refresh / includes / services / classes / class-migration-service.php

class-migration-service.php in Force Refresh 3.2.0, at includes/services/classes/class-migration-service.php

90 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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