db = $db ?? $GLOBALS['wpdb']; } /** * Getting the fully prefixed table name. * * @return string Table name. */ public function name(): string { return $this->db->prefix . Config::TOKENS_TABLE; } /** * Creating or updating the table. * * The dbDelta() parser cannot take %i; the interpolated name is prefix + constant only. */ public function install(): void { $table_name = $this->name(); $charset_collate = $this->db->get_charset_collate(); $sql = "CREATE TABLE {$table_name} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, token_hash char(64) NOT NULL, expires_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY token_hash (token_hash), KEY expires_at (expires_at) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); } /** * Dropping the table. */ public function drop(): void { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Dropping a custom table; there is no core API for it and nothing to cache. $this->db->query( $this->db->prepare( 'DROP TABLE IF EXISTS %i', $this->name() ) ); } /** * Checking whether the table is present. * * @return bool Whether the table exists. */ public function exists(): bool { $table_name = $this->name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Schema probe on a custom table; no core API, and caching would defeat the check. $found = $this->db->get_var( $this->db->prepare( 'SHOW TABLES LIKE %s', $this->db->esc_like( $table_name ) ) ); return $table_name === $found; } }