| 1 |
<?php |
| 2 |
/** |
| 3 |
* Sync store health checks. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS\Sync |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\Sync; |
| 9 |
|
| 10 |
/** |
| 11 |
* Checks whether the sync store tables are installed. |
| 12 |
*/ |
| 13 |
final class Health { |
| 14 |
public const SYNC_JOURNAL_TABLE = 'wcpos_sync_journal'; |
| 15 |
public const STORED_DIGEST_TABLE = 'wcpos_sync_stored_digest'; |
| 16 |
public const MUTATIONS_TABLE = 'wcpos_sync_mutations'; |
| 17 |
/** Schema-install retry hint exposed to WCPOS clients. */ |
| 18 |
public const RETRY_AFTER_SECONDS = 30; |
| 19 |
|
| 20 |
/** |
| 21 |
* Check whether a database table exists. |
| 22 |
* |
| 23 |
* @param string $table Fully qualified table name. |
| 24 |
*/ |
| 25 |
public static function table_exists( string $table ): bool { |
| 26 |
global $wpdb; |
| 27 |
|
| 28 |
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- The known table name is escaped for LIKE and must not be double-escaped by prepare(). |
| 29 |
return $table === $wpdb->get_var( "SHOW TABLES LIKE '" . $wpdb->esc_like( $table ) . "'" ); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Get the fully qualified sync store table names. |
| 34 |
* |
| 35 |
* @return string[] Sync store table names. |
| 36 |
*/ |
| 37 |
public static function required_tables(): array { |
| 38 |
global $wpdb; |
| 39 |
|
| 40 |
return array( |
| 41 |
$wpdb->prefix . self::SYNC_JOURNAL_TABLE, |
| 42 |
$wpdb->prefix . self::STORED_DIGEST_TABLE, |
| 43 |
$wpdb->prefix . self::MUTATIONS_TABLE, |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Get sync store tables that have not been installed. |
| 49 |
* |
| 50 |
* @return string[] Missing sync store table names. |
| 51 |
*/ |
| 52 |
public static function missing_tables(): array { |
| 53 |
$missing_tables = array(); |
| 54 |
|
| 55 |
foreach ( self::required_tables() as $table ) { |
| 56 |
if ( ! self::table_exists( $table ) ) { |
| 57 |
$missing_tables[] = $table; |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
return $missing_tables; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Check whether all required sync store tables exist. |
| 66 |
*/ |
| 67 |
public static function is_healthy(): bool { |
| 68 |
return 0 === \count( self::missing_tables() ); |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Get the error returned when the sync store is unavailable. |
| 73 |
*/ |
| 74 |
public static function unhealthy_error(): \WP_Error { |
| 75 |
return new \WP_Error( |
| 76 |
'wcpos_sync_unavailable', |
| 77 |
__( 'The WCPOS sync store is not installed yet (initialising or a schema install failed). Retry shortly.', 'woocommerce-pos' ), |
| 78 |
array( |
| 79 |
'status' => 503, |
| 80 |
'retry_after_seconds' => self::RETRY_AFTER_SECONDS, |
| 81 |
) |
| 82 |
); |
| 83 |
} |
| 84 |
} |
| 85 |
|