Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Add Docs quickstart (from DevSite) * adds docs api samples * makes cache compatible with php 5.6 * updates tests for docs samples * uses environment variable to determine credentials.json location * addresses review comments * new lines
- Loading branch information
Showing
8 changed files
with
322 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
access_token.cache |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Google Docs API Samples | ||
|
||
To run the samples in this directory, complete the steps described in the [Google Docs API Quickstart](https://developers.google.com/docs/api/quickstart/php), and in about five minutes you'll have a simple PHP command-line application that makes requests to the Google Docs API. | ||
|
||
### Install Composer Globally | ||
|
||
Before running this quickstart, be sure you have [Composer installed globally](https://getcomposer.org/doc/00-intro.md#globally). | ||
|
||
```sh | ||
composer install | ||
``` | ||
|
||
### Download Developer Credentials | ||
|
||
- Follow the steps in the quickstart instructions to download your developer | ||
credentials and save them in a file called `credentials.json` in this | ||
directory. | ||
|
||
## Run | ||
|
||
Run the samples by executing `extract_text.php` or `output_as_json.php` and providing | ||
your [Document ID](https://developers.google.com/docs/api/how-tos/overview#document_id) as | ||
the first argument. | ||
|
||
```sh | ||
php extract_text.php YOUR_DOCUMENT_ID | ||
php output_as_json.php YOUR_DOCUMENT_ID | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"require": { | ||
"google/apiclient": "^2.2", | ||
"duncan3dc/cache": "~0.4" | ||
}, | ||
"require-dev": { | ||
"google/cloud-tools": "^0.8", | ||
"phpunit/phpunit": "~5" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
<?php | ||
/** | ||
* Copyright 2019 Google LLC. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
/** | ||
* For instructions on how to run the full sample: | ||
* | ||
* @see https://github.com/gsuitedevs/docs-api-samples/tree/master/php/README.md | ||
*/ | ||
|
||
// Include Google Cloud dependendencies using Composer | ||
require_once __DIR__ . '/vendor/autoload.php'; | ||
|
||
if (count($argv) != 2) { | ||
return printf("Usage: php %s DOCUMENT_ID\n", basename(__FILE__)); | ||
} | ||
list($_, $documentId) = $argv; | ||
|
||
# [START docs_extract_text] | ||
// $documentId = 'YOUR_DOCUMENT_ID'; | ||
|
||
/** | ||
* Create an authorized API client. | ||
* Be sure you've set up your OAuth2 consent screen at | ||
* https://console.cloud.google.com/apis/credentials/consent | ||
*/ | ||
$client = new Google_Client(); | ||
$client->setScopes(Google_Service_Docs::DOCUMENTS_READONLY); | ||
$client->setAuthConfig('credentials.json'); | ||
$client->setAccessType('offline'); | ||
|
||
// You can use any PSR-6 compatible cache | ||
$fileCache = new duncan3dc\Cache\FilesystemPool(__DIR__); | ||
|
||
$fetchAccessTokenFunc = function() use ($client, $fileCache) { | ||
// Load previously authorized credentials from a file. | ||
if ($accessToken = $fileCache->get('access_token')) { | ||
return $accessToken; | ||
} | ||
// 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); | ||
$fileCache->set('access_token', $accessToken); | ||
|
||
return $accessToken; | ||
}; | ||
|
||
// Load the access token into the client | ||
$client->setAccessToken($fetchAccessTokenFunc()); | ||
|
||
// Refresh the token if it's expired. | ||
if ($client->isAccessTokenExpired()) { | ||
$accessToken = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); | ||
$fileCache->set('access_token', $accessToken); | ||
} | ||
|
||
/** | ||
* Returns the text in the given ParagraphElement. | ||
* | ||
* @param $element a ParagraphElement from a Google Doc. | ||
*/ | ||
function read_paragraph_element($element) | ||
{ | ||
if (!$textRun = $element->getTextRun()) { | ||
return ''; | ||
} | ||
return $textRun->content; | ||
} | ||
|
||
/** | ||
* Securses through a list of Structural Elements to read a document's text where text may be | ||
* in nested elements. | ||
* | ||
* @param $elements A list of Structural Elements. | ||
*/ | ||
function read_structural_elements($elements) | ||
{ | ||
$text = ''; | ||
foreach ($elements as $value) { | ||
if ($paragraph = $value->getParagraph()) { | ||
$elements = $paragraph->getElements(); | ||
foreach ($elements as $element) { | ||
$text .= read_paragraph_element($element); | ||
} | ||
} elseif ($table = $value->getTable()) { | ||
// The text in table cells are nested in Structural Elements and tables may be nested. | ||
foreach ($table->getTableRows() as $row) { | ||
foreach ($row->getTableCells() as $cell) { | ||
$text .= read_structural_elements($cell->getContent()); | ||
} | ||
} | ||
} elseif ($toc = $value->getTableOfContents()) { | ||
$text .= read_structural_elements($toc->getContent()); | ||
} | ||
} | ||
|
||
return $text; | ||
} | ||
|
||
// Fetch the document and print all text elements | ||
$service = new Google_Service_Docs($client); | ||
$doc = $service->documents->get($documentId); | ||
echo read_structural_elements($doc->getBody()->getContent()); | ||
# [END docs_extract_text] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
<?php | ||
/** | ||
* Copyright 2019 Google LLC. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
/** | ||
* For instructions on how to run the full sample: | ||
* | ||
* @see https://github.com/gsuitedevs/docs-api-samples/tree/master/php/README.md | ||
*/ | ||
|
||
// Include Google Cloud dependendencies using Composer | ||
require_once __DIR__ . '/vendor/autoload.php'; | ||
|
||
if (count($argv) != 2) { | ||
return printf("Usage: php %s DOCUMENT_ID\n", basename(__FILE__)); | ||
} | ||
list($_, $documentId) = $argv; | ||
|
||
# [START docs_output_as_json] | ||
// $documentId = 'YOUR_DOCUMENT_ID'; | ||
|
||
/** | ||
* Create an authorized API client. | ||
* Be sure you've set up your OAuth2 consent screen at | ||
* https://console.cloud.google.com/apis/credentials/consent | ||
*/ | ||
$client = new Google_Client(); | ||
$client->setScopes(Google_Service_Docs::DOCUMENTS_READONLY); | ||
$client->setAuthConfig('credentials.json'); | ||
$client->setAccessType('offline'); | ||
|
||
// You can use any PSR-6 compatible cache | ||
$fileCache = new duncan3dc\Cache\FilesystemPool(__DIR__); | ||
|
||
$fetchAccessTokenFunc = function() use ($client, $fileCache) { | ||
// Load previously authorized credentials from a file. | ||
if ($accessToken = $fileCache->get('access_token')) { | ||
return $accessToken; | ||
} | ||
// 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); | ||
$fileCache->set('access_token', $accessToken); | ||
|
||
return $accessToken; | ||
}; | ||
|
||
// Load the access token into the client | ||
$client->setAccessToken($fetchAccessTokenFunc()); | ||
|
||
// Refresh the token if it's expired. | ||
if ($client->isAccessTokenExpired()) { | ||
$accessToken = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); | ||
$fileCache->set('access_token', $accessToken); | ||
} | ||
|
||
// Fetch the document and print the results as formatted JSON | ||
$service = new Google_Service_Docs($client); | ||
$doc = $service->documents->get($documentId); | ||
print(json_encode((array) $doc, JSON_PRETTY_PRINT)); | ||
# [END docs_output_as_json] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!-- | ||
Copyright 2019 Google LLC. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
--> | ||
<phpunit bootstrap="./vendor/autoload.php"> | ||
<testsuites> | ||
<testsuite name="Google Docs PHP Samples"> | ||
<directory>test</directory> | ||
</testsuite> | ||
</testsuites> | ||
<logging> | ||
<log type="coverage-clover" target="build/logs/clover.xml"/> | ||
</logging> | ||
</phpunit> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
<?php | ||
/** | ||
* Copyright 2018 Google LLC. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
use PHPUnit\Framework\TestCase; | ||
|
||
class samplesTest extends TestCase | ||
{ | ||
// Document ID for testing | ||
private static $documentId = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE'; | ||
|
||
public function setUp() | ||
{ | ||
if (!file_exists($credsFile = __DIR__ . '/../credentials.json')) { | ||
$this->markTestSkipped(sprintf('Save your client credentials to %s', $credsFile)); | ||
} | ||
} | ||
|
||
public function testExtractTest() | ||
{ | ||
$output = $this->runSnippet('extract_text', [self::$documentId]); | ||
$this->assertNotContains('Docs API Quickstart', $output); | ||
$this->assertContains('Sample doc', $output); | ||
} | ||
|
||
public function testOutputAsJson() | ||
{ | ||
$output = $this->runSnippet('output_as_json', [self::$documentId]); | ||
$document = json_decode($output, true); | ||
$this->assertArrayHasKey('title', $document); | ||
$this->assertEquals('Docs API Quickstart', $document['title']); | ||
} | ||
|
||
private function runSnippet($sampleName, $params = []) | ||
{ | ||
$argv = array_merge([0], $params); | ||
ob_start(); | ||
require __DIR__ . "/../$sampleName.php"; | ||
return ob_get_clean(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters