-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-object-type-google-sheet.php
387 lines (300 loc) · 10.1 KB
/
class-object-type-google-sheet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php
/**
* @package gp-populate-anything-google-sheets
* @copyright Copyright (c) 2021-2022, Gravity Wiz, LLC
* @author Gravity Wiz <[email protected]>
* @license GPLv2
* @link https://github.com/gravitywiz/gp-populate-anything-google-sheets
*/
if ( ! defined( 'ABSPATH' ) ) {
die();
}
use \GP_Populate_Anything_Google_Sheets\Dependencies\Google_Client as Google_Client;
use \GP_Populate_Anything_Google_Sheets\Dependencies\Google\Service\Sheets as Google_Service_Sheets;
use \GP_Populate_Anything_Google_Sheets\Dependencies\Google\Service\Drive as Google_Service_Drive;
class GPPA_Object_Type_Google_Sheet extends GPPA_Object_Type {
const ROW_NUMBER_ID = 'Row Number';
protected $google_client;
protected $service_sheets;
protected $service_drive;
public $sheet_values_runtime_cache;
public function __construct( $id ) {
parent::__construct( $id );
$addon = GPPA_Google_Sheets::get_instance();
$json_key = $addon->get_plugin_setting( 'gcp_service_account_json' );
if ( ! $this->validate_json_key( $json_key ) ) {
return;
}
$this->google_client = new Google_Client( array(
'credentials' => $json_key,
) );
$this->google_client->useApplicationDefaultCredentials();
$this->google_client->addScope( array(
Google_Service_Sheets::SPREADSHEETS_READONLY,
Google_Service_Drive::DRIVE_READONLY,
) );
$this->service_sheets = new Google_Service_Sheets( $this->google_client );
$this->service_drive = new Google_Service_Drive( $this->google_client );
add_action( 'gppa_pre_object_type_query_google_sheet', array( $this, 'add_filter_hooks' ) );
}
public function validate_json_key( $json_key ) {
$key = GPPA_Google_Sheets::maybe_decode_json( $json_key );
if ( ! $key ) {
gppa_google_sheets()->log_debug( __METHOD__ . '(): No key provided.' );
return false;
}
if ( rgar( $key, 'type' ) !== 'service_account' ) {
gppa_google_sheets()->log_debug( sprintf( __METHOD__ . '(): Key is not of the correct type. Type required: "service_account" Type provided: "%s".', rgar( $key, 'type' ) ) );
return false;
}
if ( ! rgar( $key, 'private_key' ) ) {
gppa_google_sheets()->log_debug( __METHOD__ . '(): A private key was not provided.' );
return false;
}
return true;
}
public function add_filter_hooks() {
add_filter( 'gppa_object_type_google_sheet_filter', array( $this, 'process_filter_default' ), 10, 4 );
}
public function get_object_id( $object, $primary_property_value = null ) {
return $object[ self::ROW_NUMBER_ID ];
}
public function get_label() {
return esc_html__( 'Google Sheet', 'gp-populate-anything' );
}
public function get_primary_property() {
return array(
'id' => 'spreadsheet',
'label' => esc_html__( 'Spreadsheets', 'gp-populate-anything' ),
'callable' => array( $this, 'get_spreadsheets' ),
);
}
public function get_spreadsheets() {
$available_sheets = array();
foreach ( $this->service_drive->files->listFiles() as $file ) {
if ( $file['mimeType'] !== 'application/vnd.google-apps.spreadsheet' ) {
continue;
}
$available_sheets[ $file['id'] ] = $file['name'];
}
return $available_sheets;
}
public function get_groups() {
return array();
}
/**
* @param string $spreadsheet_id
* @param null|Google\Service\Sheets\Sheet $sheet
*
* @return array
*/
public function get_sheet_raw_values( $spreadsheet_id, $sheet = null ) {
if ( ! $this->service_sheets ) {
return array();
}
if ( ! empty( $this->sheet_values_runtime_cache[ $spreadsheet_id ] ) ) {
return $this->sheet_values_runtime_cache[ $spreadsheet_id ];
}
try {
$spreadsheet = $this->service_sheets->spreadsheets->get( $spreadsheet_id );
$sheets = $spreadsheet->getSheets();
// Limitation: use first available sheet. Ideally we would have the ability to drill down in primary properties
// @todo maybe we list all spreadsheets and their sheets as primary properties?
if ( ! $sheet ) {
$sheet = apply_filters( 'gppa_google_sheets_selected_sheet', $sheets[0], $sheets, $spreadsheet_id );
}
$response = $this->service_sheets->spreadsheets_values->get( $spreadsheet_id, $sheet->getProperties()->title );
$values = $response->getValues();
foreach ( $values as $value_index => $value ) {
if ( $value_index === 0 ) {
array_unshift( $values[ $value_index ], self::ROW_NUMBER_ID );
continue;
}
// Add row number to values to serve as the ID of the object.
array_unshift( $values[ $value_index ], $value_index );
}
$this->sheet_values_runtime_cache[ $spreadsheet_id ] = $values;
return $values;
} catch ( Exception $e ) {
error_log( 'Unable to fetch from Google Sheets: ' . $e->getMessage() );
return array();
}
}
/**
* Get columns from first row of sheet.
*
* @param string $spreadsheet_id
* @param null|Google\Service\Sheets\Sheet $sheet
*
* @return string[]
*/
public function get_sheet_columns( $spreadsheet_id, $sheet = null ) {
$values = $this->get_sheet_raw_values( $spreadsheet_id, $sheet );
if ( empty( $values ) ) {
return array();
}
return $values[0];
}
/**
* Combine row data with columns and return associative array.
*
* @param string $spreadsheet_id
* @param null|Google\Service\Sheets\Sheet $sheet
*
* @return array
*/
public function get_sheet_rows( $spreadsheet_id, $sheet = null ) {
$transient_key = 'gppa_google_sheets_rows_' . $spreadsheet_id;
$cached_rows = get_transient( $transient_key );
if ( ! empty( $cached_rows ) ) {
return $cached_rows;
}
$values = array_slice( $this->get_sheet_raw_values( $spreadsheet_id, $sheet ), 1 );
$columns = $this->get_sheet_columns( $spreadsheet_id, $sheet );
$column_count = count( $columns );
$sheet_rows = array_map( function ( $row ) use ( $columns, $column_count ) {
return array_combine( $columns, array_slice( array_pad( $row, $column_count, '' ), 0, $column_count ) );
}, $values );
$expiration_time = apply_filters( 'gpaa_google_sheets_cached_rows_expiration', 60 );
set_transient( $transient_key, $sheet_rows, $expiration_time );
return $sheet_rows;
}
/**
* @param string|null $spreadsheet_id
*
* @return array
*/
public function get_properties( $spreadsheet_id = null ) {
$properties = array();
if ( ! $spreadsheet_id ) {
return array( $properties );
}
$columns = $this->get_sheet_columns( $spreadsheet_id );
if ( ! $columns ) {
return array( $properties );
}
/**
* Extract column names from the first row.
*/
foreach ( $columns as $column ) {
$properties[ $column ] = array(
'label' => $column,
'value' => $column,
'orderby' => true,
'callable' => '__return_empty_array',
'operators' => array(
'is',
'isnot',
'contains',
'is_in',
'is_not_in',
),
);
}
return $properties;
}
public function process_filter_default( $search, $args ) {
/**
* @var $filter_value
* @var $filter
* @var $filter_group
* @var $filter_group_index
* @var $primary_property_value
* @var $property
* @var $property_id
*/
extract( $args );
$search[ $filter_group_index ][] = array(
'property' => $property_id,
'operator' => $filter['operator'],
'value' => $filter_value,
);
return $search;
}
public function perform_search( $var, $search ) {
$var_value = is_array( $var[ $search['property'] ] ) ? array_map( 'strtolower', $var[ $search['property'] ] )
: strtolower( $var[ $search['property'] ] );
$search_value = is_array( $search['value'] ) ? array_map( 'strtolower', $search['value'] ) : strtolower( $search['value'] );
switch ( $search['operator'] ) {
case 'is':
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
return ( $var_value == $search_value );
case 'isnot':
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
return ( $var_value != $search_value );
case 'is_in':
// phpcs:ignore WordPress.PHP.StrictInArray.FoundNonStrictFalse
return in_array( $var_value, $search_value, false );
case 'is_not_in':
// phpcs:ignore WordPress.PHP.StrictInArray.FoundNonStrictFalse
return ! in_array( $var_value, $search_value, false );
case 'contains':
return ( strpos( $var_value, $search_value ) !== false );
default:
throw new Error( 'Invalid operator provided.' );
}
}
/**
* @param $var
* @param $search_params
*
* @return bool
* @todo Move PHP based filtering and ordering into an Object Type that can be easily extended.
*
* Each search group is an OR
*
* If everything matches in one group, we can immediately bail out as we have a positive match.
*
*/
public function search( $var, $search_params ) {
foreach ( $search_params as $search_group ) {
if ( is_array( $search_group ) ) {
foreach ( $search_group as $search ) {
$matches_group = $this->perform_search( $var, $search );
if ( ! $matches_group ) {
return false;
}
}
}
}
return true;
}
public function query( $args ) {
/**
* @var $filter_value
* @var $filter
* @var $filter_group
* @var $filter_group_index
* @var $primary_property_value
* @var $property
* @var $property_id
* @var $ordering
*/
extract( $args );
$results = $this->get_sheet_rows( $primary_property_value );
$search_params = $this->process_filter_groups( $args );
if ( ! empty( $search_params ) ) {
$results = array_values( array_filter( $results, function ( $var ) use ( $search_params ) {
return $this->search( $var, $search_params );
} ) );
}
$orderby = rgar( $ordering, 'orderby' );
$order = strtolower( rgar( $ordering, 'order', 'ASC' ) );
if ( ! empty( $orderby ) && count( $results ) && array_key_exists( $orderby, $results[0] ) ) {
if ( $order === 'rand' ) {
shuffle( $results );
} else {
array_multisort( array_column( $results, $orderby ), $order === 'desc' ? SORT_DESC : SORT_ASC, $results );
}
}
$query_limit = gp_populate_anything()->get_query_limit( $this, $args['field'] );
$query_results = array_slice( $results, 0, $query_limit );
return $query_results;
}
public function get_object_prop_value( $object, $prop ) {
if ( ! isset( $object[ $prop ] ) ) {
return null;
}
return $object[ $prop ];
}
}