/**
* usefull: https://www.nidup.io/blog/manipulate-google-sheets-in-php-with-api
*/
-class GSheetSync {
-
+class GSheetSync
+{
private $service;
private $spreadsheetId;
- function __construct(string $credentialsPath, string $spreadsheetId)
+ public function __construct(string $credentialsPath, string $spreadsheetId)
{
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API');
$client->setAuthConfig($credentialsPath);
- $this->service = new \Google\Service\Sheets($client);
+ $this->service = new \Google\Service\Sheets($client);
$this->spreadsheetId = $spreadsheetId;
}
* @param string $range the name of the Sheet to get all the rows, extra args to pick. EX: 'Sheet1!A1:F10'
* @return string | false JSON or false if failure
*/
- function get(string $range): string | false {
+ public function get(string $range): string | false
+ {
// get all the rows of a sheet
$response = $this->service->spreadsheets_values->get($this->spreadsheetId, $range);
- $rows = $response->getValues();
+ $rows = $response->getValues();
// Remove the first one that contains headers
$headers = array_shift($rows);
$array = [];
foreach ($rows as $row) {
# fill blank spaces at end if needed
- while (count($headers) > count($row))
+ while (count($headers) > count($row)) {
$row[] = null;
+ }
$array[] = array_combine($headers, $row);
}
* @param string $sheet sheet of the document, where to append the new row
* @param array $arr columns to append at the end of the document
*/
- function put(string $sheet, array $row): void {
+ public function put(string $sheet, array $row): void
+ {
$valueRange = new \Google\Service\Sheets\ValueRange();
$valueRange->setValues([$row]);
$filename = generateFilename($_ENV["sheetId"], $sheet);
if (fileExpired($filename)) {
$sheetSync = new GSheetSync($_ENV["credentialsPath"], $_ENV["sheetId"]);
- $res = $sheetSync->get($sheet);
+ $res = $sheetSync->get($sheet);
$etag = md5($res);
header('ETag: ' . $etag);
$filename = generateFilename($_ENV["sheetId"], $sheet);
if (fileExpired($filename)) {
$sheetSync = new GSheetSync($_ENV["credentialsPath"], $_ENV["sheetId"]);
- $res = $sheetSync->get($sheet);
+ $res = $sheetSync->get($sheet);
// dont make the user wait, print the json
$etag = md5($res);
$filetime = filemtime($filename);
// if file does not exist counts as expired
- if (!$filetime) return true;
+ if (!$filetime) {
+ return true;
+ }
// if file older than TTL minutes IS expired
- if ($filetime < time() - TTL) return true;
+ if ($filetime < time() - TTL) {
+ return true;
+ }
// else file is NOT expired
return false;
return !(md5_file($oldFilePath) == md5($newFileString));
}
-
/**
* Sends an 304 Not Modified header if the ETag matches the sent one
*/
if ($_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
http_response_code(304);
header('HTTP/1.1 304 Not Modified');
- if ($die)
+ if ($die) {
exit();
+ }
}
}
}