66 lines
1.5 KiB
PHP
66 lines
1.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Google;
|
|
|
|
use Google\Client;
|
|
use Google\Service\Sheets;
|
|
use GuzzleHttp\Client as GuzzleClient;
|
|
|
|
class GoogleSheetsService
|
|
{
|
|
private Sheets $service;
|
|
private string $spreadsheetId;
|
|
private string $sheetName;
|
|
|
|
public function __construct(string $spreadsheetId, string $sheetName)
|
|
{
|
|
$guzzle = new GuzzleClient([
|
|
'curl' => [
|
|
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
|
|
]
|
|
]);
|
|
|
|
$client = new Client();
|
|
$client->setHttpClient($guzzle);
|
|
$client->setAuthConfig(__DIR__ . '/../../../storage/google-service-account.json');
|
|
$client->setScopes([Sheets::SPREADSHEETS]);
|
|
|
|
$this->service = new Sheets($client);
|
|
|
|
$this->spreadsheetId = $spreadsheetId;
|
|
$this->sheetName = $sheetName;
|
|
}
|
|
|
|
public function getRowsRaw(): array
|
|
{
|
|
$range = "'{$this->sheetName}'!A:Z";
|
|
|
|
$response = $this->service->spreadsheets_values->get(
|
|
$this->spreadsheetId,
|
|
$range
|
|
);
|
|
|
|
$values = $response->getValues() ?? [];
|
|
|
|
$rows = [];
|
|
|
|
foreach ($values as $i => $row) {
|
|
|
|
$rowNum = $i + 1;
|
|
|
|
if ($rowNum === 1) continue;
|
|
|
|
$item = ['_row_number' => $rowNum];
|
|
|
|
foreach (range('A','Z') as $idx=>$col) {
|
|
$item[$col] = $row[$idx] ?? null;
|
|
}
|
|
|
|
$rows[] = $item;
|
|
}
|
|
|
|
return $rows;
|
|
}
|
|
} |