81 lines
2.1 KiB
PHP
81 lines
2.1 KiB
PHP
<?php namespace App\Libraries;
|
|
|
|
use Google_Client;
|
|
use Google_Service_Sheets;
|
|
use Google_Service_Drive;
|
|
use Google_Service_Sheets_ValueRange;
|
|
|
|
class GoogleSheetLib
|
|
{
|
|
protected Google_Client $client;
|
|
protected Google_Service_Sheets $sheets;
|
|
protected Google_Service_Drive $drive;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->client = new Google_Client();
|
|
|
|
// Service account JSON
|
|
$this->client->setAuthConfig(
|
|
ROOTPATH . 'gdrive-demo-394007-5b1d856b0c5b.json'
|
|
);
|
|
|
|
// IMPORTANT for service account
|
|
$this->client->useApplicationDefaultCredentials();
|
|
|
|
// Required scopes
|
|
$this->client->addScope([
|
|
Google_Service_Drive::DRIVE,
|
|
Google_Service_Sheets::SPREADSHEETS
|
|
]);
|
|
|
|
// Init services
|
|
$this->sheets = new Google_Service_Sheets($this->client);
|
|
$this->drive = new Google_Service_Drive($this->client);
|
|
}
|
|
|
|
/* ===================== READ ===================== */
|
|
|
|
public function read(string $spreadsheetId, string $range = 'Sheet1')
|
|
{
|
|
$response = $this->sheets
|
|
->spreadsheets_values
|
|
->get($spreadsheetId, $range);
|
|
|
|
return $response->getValues() ?? [];
|
|
}
|
|
|
|
/* ===================== WRITE ===================== */
|
|
|
|
public function write(string $spreadsheetId, array $values, string $range = 'Sheet1')
|
|
{
|
|
$body = new Google_Service_Sheets_ValueRange([
|
|
'values' => $values
|
|
]);
|
|
|
|
$this->sheets
|
|
->spreadsheets_values
|
|
->update(
|
|
$spreadsheetId,
|
|
$range,
|
|
$body,
|
|
['valueInputOption' => 'RAW']
|
|
);
|
|
|
|
return true;
|
|
}
|
|
|
|
/* ===================== DOWNLOAD ===================== */
|
|
|
|
public function downloadExcel(string $spreadsheetId)
|
|
{
|
|
$response = $this->drive->files->export(
|
|
$spreadsheetId,
|
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
['alt' => 'media']
|
|
);
|
|
|
|
return $response->getBody()->getContents();
|
|
}
|
|
}
|