| 1 |
<?php |
| 2 |
|
| 3 |
namespace SureCart\Database; |
| 4 |
|
| 5 |
/** |
| 6 |
* Table class for creating custom tables. |
| 7 |
*/ |
| 8 |
class Table { |
| 9 |
/** |
| 10 |
* Create a database table |
| 11 |
* |
| 12 |
* @param string $name Table name. |
| 13 |
* @param string $columns Table columns. |
| 14 |
* @param integer $version Table version. |
| 15 |
* @param array $opts Table options. |
| 16 |
* @return void |
| 17 |
*/ |
| 18 |
public function create( $name, $columns, $version = 1, $opts = [] ) { |
| 19 |
$current_version = (int) get_option( "{$name}_database_version", 0 ); |
| 20 |
|
| 21 |
if ( $version === $current_version ) { |
| 22 |
return; |
| 23 |
} |
| 24 |
|
| 25 |
global $wpdb; |
| 26 |
|
| 27 |
$full_table_name = $wpdb->prefix . $name; |
| 28 |
|
| 29 |
$opts = wp_parse_args( |
| 30 |
$opts, |
| 31 |
[ |
| 32 |
'table_options' => '', |
| 33 |
] |
| 34 |
); |
| 35 |
|
| 36 |
$charset_collate = ''; |
| 37 |
if ( $wpdb->has_cap( 'collation' ) ) { |
| 38 |
if ( ! empty( $wpdb->charset ) ) { |
| 39 |
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; |
| 40 |
} |
| 41 |
if ( ! empty( $wpdb->collate ) ) { |
| 42 |
$charset_collate .= " COLLATE $wpdb->collate"; |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
$table_options = $charset_collate . ' ' . $opts['table_options']; |
| 47 |
|
| 48 |
// use dbDelta to create the table. |
| 49 |
require_once ABSPATH . 'wp-admin/includes/upgrade.php'; |
| 50 |
$created = dbDelta( "CREATE TABLE $full_table_name ( $columns ) $table_options" ); |
| 51 |
update_option( "{$name}_database_version", $version ); |
| 52 |
return $created; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Drops the table and database option |
| 57 |
* |
| 58 |
* @param string $name The name of the table to drop. |
| 59 |
* @return boolean Whether the table was dropped. |
| 60 |
*/ |
| 61 |
public function drop( $name ) { |
| 62 |
global $wpdb; |
| 63 |
$dropped = $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS `%s`', $name ) ); |
| 64 |
if ( true === $dropped ) { |
| 65 |
delete_option( "{$name}_database_version" ); |
| 66 |
} |
| 67 |
return true === $dropped; |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Does the database table exist? |
| 72 |
* |
| 73 |
* @param string $name Table name. |
| 74 |
* |
| 75 |
* @return boolean |
| 76 |
*/ |
| 77 |
public function exists( $name ) { |
| 78 |
global $wpdb; |
| 79 |
$table_name = $wpdb->prefix . $name; |
| 80 |
return $table_name === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) ) ); |
| 81 |
} |
| 82 |
} |
| 83 |
|