Skip to content

Commit

Permalink
adds docs api samples (#47)
Browse files Browse the repository at this point in the history
* 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
bshaffer authored and asrivas committed Aug 24, 2019
1 parent 6f984e6 commit b00fd29
Show file tree
Hide file tree
Showing 8 changed files with 322 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/samples/.gitignore
@@ -0,0 +1 @@
access_token.cache
28 changes: 28 additions & 0 deletions docs/samples/README.md
@@ -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
```
10 changes: 10 additions & 0 deletions docs/samples/composer.json
@@ -0,0 +1,10 @@
{
"require": {
"google/apiclient": "^2.2",
"duncan3dc/cache": "~0.4"
},
"require-dev": {
"google/cloud-tools": "^0.8",
"phpunit/phpunit": "~5"
}
}
122 changes: 122 additions & 0 deletions docs/samples/extract_text.php
@@ -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]
79 changes: 79 additions & 0 deletions docs/samples/output_as_json.php
@@ -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]
26 changes: 26 additions & 0 deletions docs/samples/phpunit.xml.dist
@@ -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>
54 changes: 54 additions & 0 deletions docs/samples/test/samplesTest.php
@@ -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();
}
}
3 changes: 2 additions & 1 deletion test.sh
Expand Up @@ -17,8 +17,9 @@ set -ex
# Find every directory with a phpunit.xml file and run phpunit in that directory
find . -name 'phpunit.xml*' -not -path '*vendor/*' -exec dirname {} \; | while read DIR
do
ln -s $GOOGLE_APPLICATION_CREDENTIALS $DIR
pushd ${DIR}
composer install
vendor/bin/phpunit
vendor/bin/phpunit -v
popd;
done

0 comments on commit b00fd29

Please sign in to comment.