Skip to content

Instantly share code, notes, and snippets.

@mattcdavis1
Last active February 17, 2021 01:48
Show Gist options
  • Save mattcdavis1/af4ccc79ca1b75da1b8d92ca02a48aa8 to your computer and use it in GitHub Desktop.
Save mattcdavis1/af4ccc79ca1b75da1b8d92ca02a48aa8 to your computer and use it in GitHub Desktop.
Google Docs Replace Fails
<?php
namespace App\Console\Commands\Google;
use Google_Client;
use Google_Http_Batch;
use Google_Service_Docs_BatchUpdateDocumentRequest;
use Google_Service_Docs_ReplaceAllTextRequest;
use Google_Service_Docs_SubstringMatchCriteria;
use Google_Service_Docs;
use Illuminate\Console\Command;
class MergeDocCommand extends Command
{
const DOC_ID = '{DOC ID}';
protected $signature = 'google:merge-doc';
protected $description = 'Merge a Google Doc';
public function handle()
{
$this->comment('Merging Doc');
// Get the API client and construct the service object.
$client = $this->getClient();
// $this->printDocumentTitle($client);
$this->mergeDocument($client);
}
protected function mergeDocument($client)
{
$service = new Google_Service_Docs($client);
$batchRequest = new Google_Service_Docs_BatchUpdateDocumentRequest($client);
$replacements = ['{!IXO__Case__c.Name}' => 'Rob Lowe v.'];
foreach ($replacements as $tokenText => $replacementText) {
// Prints the title of the requested doc:
$request = new Google_Service_Docs_ReplaceAllTextRequest;
$containsText = new Google_Service_Docs_SubstringMatchCriteria();
$containsText->setText($tokenText);
$request->setContainsText($containsText);
$request->setReplaceAllText($replacementText);
$requests[] = $request;
}
$batchRequest->setRequests($requests);
$service->documents->batchUpdate(self::DOC_ID, $batchRequest);
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
private function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Merge Doc');
$client->setScopes(Google_Service_Docs::DOCUMENTS);
$client->setAuthConfig(storage_path('google/docs/credentials.json'));
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = storage_path('google/docs/token.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
}
<?php
namespace App\Console\Commands\Google;
use Google_Client;
use Google_Http_Batch;
use Google_Service_Docs_BatchUpdateDocumentRequest;
use Google_Service_Docs_ReplaceAllTextRequest;
use Google_Service_Docs_SubstringMatchCriteria;
use Google_Service_Docs;
use Illuminate\Console\Command;
class MergeDocCommand extends Command
{
const DOC_ID = '{DOC ID}';
protected $signature = 'google:merge-doc';
protected $description = 'Merge a Google Doc';
public function handle()
{
$this->comment('Merging Doc');
// Get the API client and construct the service object.
$client = $this->getClient();
// $this->printDocumentTitle($client);
$this->mergeDocument($client);
}
protected function mergeDocument($client)
{
$replacements = ['{!IXO__Case__c.Name}' => 'Rob Lowe v.'];
foreach ($replacements as $tokenText => $replacementText) {
// Prints the title of the requested doc:
$replaceAllTextRequest = new Google_Service_Docs_ReplaceAllTextRequest;
$containsText = new Google_Service_Docs_SubstringMatchCriteria();
$containsText->setText($tokenText);
$replaceAllTextRequest->setContainsText($containsText);
$replaceAllTextRequest->setReplaceText($replacementText);
$request = new Google_Service_Docs_Request();
$request->setReplaceAllText($replaceAllTextRequest);
$requests[] = $request;
}
$batchRequest = new Google_Service_Docs_BatchUpdateDocumentRequest();
$batchRequest->setRequests($requests);
$service = new Google_Service_Docs($client);
$service->documents->batchUpdate(self::DOC_ID, $batchRequest);
$doc = $service->documents->get(self::DOC_ID);
$title = $doc->getTitle();
$this->info('Title is: ' . $title);
$body = $doc->getBody();
foreach ($body->getContent() as $element) {
if ($paragraph = $element->getParagraph()) {
$elements = $paragraph->getElements();
foreach ($elements as $element) {
if ($textRun = $element->getTextRun()) {
$content = trim($textRun->getContent());
if ($content) {
$this->info('Text Run Content: ' . $content);
}
}
}
}
}
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
private function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Merge Doc');
$client->setScopes(Google_Service_Docs::DOCUMENTS);
$client->setAuthConfig(storage_path('google/docs/credentials.json'));
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = storage_path('google/docs/token.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment