Skip to content

Commit

Permalink
Merge branch 'refactor'
Browse files Browse the repository at this point in the history
  • Loading branch information
sectsect committed Oct 20, 2024
2 parents d3e84f3 + 53c8f4a commit 93f585a
Show file tree
Hide file tree
Showing 2 changed files with 161 additions and 158 deletions.
159 changes: 159 additions & 0 deletions functions/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
* @param int $paged Current page number, defaults to 1.
* @param int $pages Total number of pages, defaults to 1.
* @param int $range Number of pages to display around the current page, defaults to 2.
* @return void
*/
function google_ss2db_options_pagination( int $paged = 1, int $pages = 1, int $range = 2 ): void {
$paged = intval( $paged );
Expand Down Expand Up @@ -89,3 +90,161 @@ function google_ss2db_get_plugin_data(): array {
$plugin_data = get_plugin_data( plugin_dir_path( __DIR__ ) . 'google-spreadsheet-to-db.php' );
return $plugin_data;
}

/**
* Checks if a specific sheet exists within a list of sheets.
*
* @param Google_Service_Sheets_Sheet[] $sheets_list An array of sheet objects.
* @param string $sheet_name The name of the sheet to check for.
* @return bool Returns true if the sheet exists, false otherwise.
*/
function google_ss2db_exist_sheet( array $sheets_list, string $sheet_name ): bool {
foreach ( $sheets_list as $sheet ) {
if ( $sheet->getProperties()->getTitle() === $sheet_name ) {
return true;
}
}
return false;
}

/**
* Creates and returns a Google_Client authorized for Google Sheets and Drive APIs.
*
* @return Google_Client The authorized client object.
* @throws Exception If an error occurs during Google Client initialization.
*/
function google_ss2db_get_client(): Google_Client {
$client_secret = ( defined( 'GOOGLE_SS2DB_CLIENT_SECRET_PATH' ) ) ? GOOGLE_SS2DB_CLIENT_SECRET_PATH : '';

if ( empty( $client_secret ) ) {
wp_die( 'Client secret path is not set. Please check GOOGLE_SS2DB_CLIENT_SECRET_PATH.' );
}

if ( ! file_exists( $client_secret ) ) {
wp_die( 'Client secret file not found: ' . $client_secret );
}

putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . $client_secret );

try {
$client = new Google_Client();
$client->setApplicationName( 'Google Sheets API PHP Quickstart' );
$client->setScopes( array( Google_Service_Sheets::SPREADSHEETS, Google_Service_Sheets::DRIVE ) );
$client->setAuthConfig( $client_secret );
$client->setAccessType( 'offline' );
} catch ( Exception $e ) {
wp_die( 'Error occurred during Google Client initialization: ' . $e->getMessage() );
}

return $client;
}

/**
* Processes spreadsheet data with a header row.
*
* @param array<int, array<int, string>> $values The raw spreadsheet values.
* @return array<int, array<string, string|null>> Processed data with header keys.
*/
function google_ss2db_process_with_header( array $values ): array {
if ( empty( $values ) ) {
return array();
}

$header = array_shift( $values );
return array_map(
function ( $row ) use ( $header ) {
return array_combine( $header, array_pad( $row, count( $header ), null ) );
},
$values
);
}

/**
* Retrieves data from a specified Google Spreadsheet.
*
* @param string $worksheet_id The ID of the Google Spreadsheet.
* @param string $worksheet_name The name of the Google Spreadsheet.
* @param string $sheet_name The name of the individual sheet within the Spreadsheet.
* @param bool $has_header_row Indicates if the spreadsheet contains a header row.
* @return array<int|string, mixed> The spreadsheet data as an associative array.
* @throws Exception If the specified sheet does not exist or if there's an error retrieving data.
*/
function google_ss2db_get_value_google_spreadsheet( string $worksheet_id, string $worksheet_name, string $sheet_name, bool $has_header_row ): array {
try {
$client = google_ss2db_get_client();
$service = new Google_Service_Sheets( $client );

$spreadsheet = $service->spreadsheets->get( $worksheet_id );
$sheets = $spreadsheet->getSheets();

if ( ! google_ss2db_exist_sheet( $sheets, $sheet_name ) ) {
wp_die( 'The specified sheet does not exist. Please check the sheet name.' );
}

$response = $service->spreadsheets_values->get( $worksheet_id, $sheet_name );
$values = $response->getValues();

$data = $has_header_row ? google_ss2db_process_with_header( $values ) : $values;

return apply_filters( 'google_ss2db_before_save', $data, $worksheet_id, $worksheet_name, $sheet_name );
} catch ( Exception $e ) {
error_log( 'Error in google_ss2db_get_value_google_spreadsheet: ' . $e->getMessage() );
throw $e;
}
}

/**
* Saves data from a Google Spreadsheet to the database.
*
* @param array<string> $post_data POST data containing spreadsheet information.
* @return array<string> Contains details of the operation including the database row ID, date, worksheet identifiers, and operation result.
*/
function google_ss2db_save_spreadsheet( array $post_data ): array {
global $wpdb;
$today = new DateTime();
$timezone_string = wp_timezone_string();
if ( empty( $timezone_string ) ) {
wp_die( __( 'Error: Timezone is not set. Please check your WordPress settings.', 'google_ss2db' ) );
}
$today->setTimeZone( new DateTimeZone( $timezone_string ) );
$date = $today->format( 'Y-m-d H:i:s' );
$title = wp_unslash( $post_data['datatitle'] ?? '' );
$worksheet_id = wp_unslash( $post_data['worksheetid'] ?? '' );
$worksheet_name = wp_unslash( $post_data['worksheetname'] ?? '' );
$sheet_name = wp_unslash( $post_data['sheetname'] ?? '' );
$has_header_row = filter_var( wp_unslash( $post_data['hasheaderrow'] ?? false ), FILTER_VALIDATE_BOOLEAN );
$value = google_ss2db_get_value_google_spreadsheet( $worksheet_id, $worksheet_name, $sheet_name, $has_header_row );
$value = json_encode( $value, get_option( 'google_ss2db_dataformat' ) === 'json-unescp' ? JSON_UNESCAPED_UNICODE : 0 );

$result = $wpdb->insert(
GOOGLE_SS2DB_TABLE_NAME,
array(
'date' => $date,
'worksheet_id' => $worksheet_id,
'worksheet_name' => $worksheet_name,
'sheet_name' => $sheet_name,
'title' => $title,
'value' => $value,
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
$row_id = $wpdb->insert_id;

return array(
'id' => $row_id,
'date' => $date,
'worksheet_id' => $worksheet_id,
'worksheet_name' => $worksheet_name,
'sheet_name' => $sheet_name,
'title' => $title,
'value' => $value,
'result' => $result,
);
}
160 changes: 2 additions & 158 deletions includes/save.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,164 +32,8 @@
wp_die( 'Our Site is protected!!' );
}

/**
* Checks if a specific sheet exists within a list of sheets.
*
* @param Google_Service_Sheets_Sheet[] $sheets_list An array of sheet objects.
* @param string $sheet_name The name of the sheet to check for.
* @return bool Returns true if the sheet exists, false otherwise.
*/
function exist_sheet( array $sheets_list, string $sheet_name ): bool {
foreach ( $sheets_list as $sheet ) {
if ( $sheet->getProperties()->getTitle() === $sheet_name ) {
return true;
}
}
return false;
}

/**
* Creates and returns a Google_Client authorized for Google Sheets and Drive APIs.
*
* @return Google_Client The authorized client object.
*/
function get_client(): Google_Client {
$client_secret = ( defined( 'GOOGLE_SS2DB_CLIENT_SECRET_PATH' ) ) ? GOOGLE_SS2DB_CLIENT_SECRET_PATH : '';

if ( empty( $client_secret ) ) {
wp_die( 'Client secret path is not set. Please check GOOGLE_SS2DB_CLIENT_SECRET_PATH.' );
}

if ( ! file_exists( $client_secret ) ) {
wp_die( 'Client secret file not found: ' . $client_secret );
}

putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . $client_secret );

try {
$client = new Google_Client();
$client->setApplicationName( 'Google Sheets API PHP Quickstart' );
$client->setScopes( array( Google_Service_Sheets::SPREADSHEETS, Google_Service_Sheets::DRIVE ) );
$client->setAuthConfig( $client_secret );
$client->setAccessType( 'offline' );
} catch ( Exception $e ) {
wp_die( 'Error occurred during Google Client initialization: ' . $e->getMessage() );
}

return $client;
}

/**
* Retrieves data from a specified Google Spreadsheet.
*
* @param string $worksheet_id The ID of the Google Spreadsheet.
* @param string $worksheet_name The name of the Google Spreadsheet.
* @param string $sheet_name The name of the individual sheet within the Spreadsheet.
* @param bool $has_header_row Indicates if the spreadsheet contains a header row.
* @return array<string, mixed>|bool The spreadsheet data as an associative array if successful, or false if the sheet does not exist.
*/
function get_value_google_spreadsheet( string $worksheet_id, string $worksheet_name, string $sheet_name, bool $has_header_row ): array|bool {
$client = get_client();
$service = new Google_Service_Sheets( $client );

$spreadsheet_id = $worksheet_id;
$range = $sheet_name;

$response = $service->spreadsheets->get( $spreadsheet_id );
$sheets = $response->getSheets();

if ( ! exist_sheet( $sheets, $sheet_name ) ) {
wp_die( 'The specified sheet does not exist. Please check the sheet name.' );
}

$response = $service->spreadsheets_values->get( $spreadsheet_id, $range );
$values = $response->getValues();
$object = array();

if ( ! empty( $values ) ) {
if ( $has_header_row ) {
$header_row = $values[0];
// Remove the header row.
unset( $values[0] );

$i = 0;
foreach ( $values as $row ) {
$j = 0;
$object[ $i ] = array();

foreach ( $row as $column ) {
$object[ $i ][ $header_row[ $j ] ] = $column;
++$j;
}
++$i;
}
} else {
$object = $values;
}
}

$array = apply_filters( 'google_ss2db_before_save', $object, $worksheet_id, $worksheet_name, $sheet_name );

return $array;
}

/**
* Saves data from a Google Spreadsheet to the database.
*
* @return array<string, mixed> Contains details of the operation including the database row ID, date, worksheet identifiers, and operation result.
*/
function save_spreadsheet(): array {
global $wpdb;
$today = new DateTime();
$timezone_string = wp_timezone_string();
if ( empty( $timezone_string ) ) {
wp_die( __( 'Error: Timezone is not set. Please check your WordPress settings.', 'google_ss2db' ) );
}
$today->setTimeZone( new DateTimeZone( $timezone_string ) );
$date = $today->format( 'Y-m-d H:i:s' );
$title = wp_unslash( $_POST['datatitle'] ?? '' );
$worksheet_id = wp_unslash( $_POST['worksheetid'] ?? '' );
$worksheet_name = wp_unslash( $_POST['worksheetname'] ?? '' );
$sheet_name = wp_unslash( $_POST['sheetname'] ?? '' );
$has_header_row = wp_unslash( $_POST['hasheaderrow'] ?? false );
$value = get_value_google_spreadsheet( $worksheet_id, $worksheet_name, $sheet_name, $has_header_row );
$value = json_encode( $value, get_option( 'google_ss2db_dataformat' ) === 'json-unescp' ? JSON_UNESCAPED_UNICODE : 0 );

$result = $wpdb->insert(
GOOGLE_SS2DB_TABLE_NAME,
array(
'date' => $date,
'worksheet_id' => $worksheet_id,
'worksheet_name' => $worksheet_name,
'sheet_name' => $sheet_name,
'title' => $title,
'value' => $value,
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
)
);
$row_id = $wpdb->insert_id;

return array(
'id' => $row_id,
'date' => $date,
'worksheet_id' => $worksheet_id,
'worksheet_name' => $worksheet_name,
'sheet_name' => $sheet_name,
'title' => $title,
'value' => $value,
'result' => $result,
);
}

$data = save_spreadsheet();
apply_filters( 'google_ss2db_after_save', $data );
$data = google_ss2db_save_spreadsheet( $_POST );
$data = apply_filters( 'google_ss2db_after_save', $data );

$bool = (bool) $data['result'];
$referer = wp_unslash( $_POST['_wp_http_referer'] );
Expand Down

0 comments on commit 93f585a

Please sign in to comment.