File: //var/www/elite/coordParser/GoogleSheet.php
<?php
namespace coordParser;
use Exception;
use Google\Client;
use Google_Service_Sheets;
use Google_Service_Sheets_BatchUpdateValuesRequest;
use Google_Service_Sheets_ValueRange;
class GoogleSheet
{
private Google_Service_Sheets $service;
private string $spreadsheetId;
private string $range;
private array $table = [];
private function createService(): Google_Service_Sheets
{
$client = new Client();
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/credentials.json');
return new Google_Service_Sheets($client);
}
private function errorExit(string $message): void
{
echo $message . PHP_EOL;
exit;
}
private function get(): array
{
try {
return $this->service->spreadsheets_values->get($this->spreadsheetId, $this->range)->getValues();
} catch (Exception $exception) {
$this->errorExit('Ошибка: ' . $exception->getMessage());
}
return [];
}
public function __construct(string $spreadsheetId, string $range)
{
$this->spreadsheetId = $spreadsheetId;
$this->range = $range;
$this->service = $this->createService();
}
/** Получение данных из Google таблицы */
public function readTable(): self
{
$table = $this->get();
$header = [];
$this->table = [];
$this->rowsCount = 0;
foreach ($table as $index => $row) {
// Формируем переменную с заголовком и вычисляем индексы нужных колонок
if (0 === $index) {
$this->table[] = $row;
$header = $row;
continue;
}
$this->rowsCount++;
// Собираем новую строку с пустыми колонками если надо, иначе Google не хочет работать
$newRow = [];
foreach ($header as $colIndex => $col) {
$newRow[$colIndex] = $row[$colIndex] ?? '';
}
$this->table[] = $newRow;
}
return $this;
}
public function addRow(array $row): self
{
$this->table[] = $row;
return $this;
}
public function setTable(array $table): self
{
$this->table = $table;
return $this;
}
public function getTable(): array
{
return $this->table;
}
/** Отправка изменений в Google таблицу */
public function commitUpdate(): self
{
$data[] = new Google_Service_Sheets_ValueRange(['range' => $this->range, 'values' => $this->table]);
$body = new Google_Service_Sheets_BatchUpdateValuesRequest(['valueInputOption' => 'RAW', 'data' => $data]);
$this->service->spreadsheets_values->batchUpdate($this->spreadsheetId, $body);
$this->rowsUpdated = 0;
return $this;
}
}