Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions appengine/php72/tasks/apps/handler/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Google Cloud Tasks Handler on App Engine Standard for PHP 7.2

The Task Handler sample application demonstrates how to handle a task from a Cloud Tasks Appengine Queue.

## Setup the sample

- Install [`composer`](https://getcomposer.org)
- Install dependencies by running:
```sh
composer install
```
- Install the [Google Cloud SDK](https://developers.google.com/cloud/sdk/).

## Deploy the sample

### Deploy with `gcloud`

Deploy the samples by doing the following:

```
gcloud config set project YOUR_PROJECT_ID
gcloud app deploy
gcloud app browse
```

The last command will open `https://{YOUR_PROJECT_ID}.appspot.com/`
in your browser. Browse to `/` to send in some logs.

### Run Locally

Run the sample locally using PHP's build-in web server:

```
# export environemnt variables locally which are set by App Engine when deployed
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

# Run PHP's built-in web server
php -S localhost:8000
```

Browse to `localhost:8000` to send in the logs.

> Note: These logs will show up under the `Global` resource since you are not
actually sending these from App Engine.

## Contributing changes

* See [CONTRIBUTING.md](../../CONTRIBUTING.md)

## Licensing

* See [LICENSE](../../LICENSE)
1 change: 1 addition & 0 deletions appengine/php72/tasks/apps/handler/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
runtime: php72
10 changes: 10 additions & 0 deletions appengine/php72/tasks/apps/handler/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"require": {
"google/cloud-tasks": "^0.4.1",
"google/cloud-logging": "^1.14"
},
"require-dev": {
"phpunit/phpunit": "^5",
"google/cloud-tools": "^0.8.5"
}
}
81 changes: 81 additions & 0 deletions appengine/php72/tasks/apps/handler/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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.
*/

// [START cloud_tasks_appengine_quickstart]

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Logging\LoggingClient;

// Create the logging client.
$logging = new LoggingClient();
// Create a PSR-3-compatible logger.
$logger = $logging->psrLogger('app', ['batchEnabled' => true]);

// Front-controller to route requests.
switch (@parse_url(https://github.com/$_SERVER['REQUEST_URI'])['path']) {
case '/':
print "Hello, World!\n";
break;
case '/task_handler':
// Taskname and Queuename are two of several useful Cloud Tasks headers available on the request.
$taskName = $_SERVER['HTTP_X_APPENGINE_TASKNAME'] ?? '';
$queueName = $_SERVER['HTTP_X_APPENGINE_QUEUENAME'] ?? '';

try {
handle_task(
$queueName,
$taskName,
file_get_contents('php://input')
);
} catch (Exception $e) {
http_response_code(400);
exit($e->getMessage());
}
break;
default:
http_response_code(404);
exit('Not Found');
}

/**
* Process a Cloud Tasks HTTP Request.
*
* @param string $queueName provides the name of the queue which dispatched the task.
* @param string $taskName provides the identifier of the task.
* @param string $body The task details from the HTTP request.
*/
function handle_task($queueName, $taskName, $body = '')
{
global $logger;

if (empty($taskName)) {
// You may use the presence of the X-Appengine-Taskname header to validate
// the request comes from Cloud Tasks.
$logger->warning('Invalid Task: No X-Appengine-Taskname request header found');
throw new Exception('Bad Request - Invalid Task');
}

$output = sprintf('Completed task: task queue(%s), task name(%s), payload(%s)', $queueName, $taskName, $body);
$logger->info($output);

// Set a non-2xx status code to indicate a failure in task processing that should be retried.
// For example, http_response_code(500) to indicate a server error.
print $output;
}

// [END cloud_tasks_appengine_quickstart]
31 changes: 31 additions & 0 deletions appengine/php72/tasks/apps/handler/phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<phpunit bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="AppEngine for PHP 7.2 tasks test">
<directory>test</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
<filter>
<whitelist>
<file>index.php</file>
</whitelist>
</filter>
</phpunit>
46 changes: 46 additions & 0 deletions appengine/php72/tasks/apps/handler/test/DeployTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?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 Google\Cloud\TestUtils\TestTrait;
use Google\Cloud\TestUtils\AppEngineDeploymentTrait;
use Google\Cloud\TestUtils\EventuallyConsistentTestTrait;
use GuzzleHttp\Exception\ClientException;

use PHPUnit\Framework\TestCase;

class DeployTest extends TestCase
{
use TestTrait;
use AppEngineDeploymentTrait;
use EventuallyConsistentTestTrait;

public function testIndex()
{
// Access the modules app top page.
$response = $this->client->get('');
$this->assertEquals('200', $response->getStatusCode());
$this->assertContains(
'Hello, World!',
$response->getBody()->getContents()
);
}

public function testTaskHandlerInvalid() {
$this->expectException(ClientException::class);
$response = $this->client->get('/task_handler');
}
}
59 changes: 36 additions & 23 deletions tasks/README.md → appengine/php72/tasks/snippets/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
# Google Cloud Tasks Pull Queue Samples
# Google Cloud Tasks App Engine Queue Samples

## THIS SAMPLE IS CURRENTLY INCOMPLETE. PLEASE REFER TO [THE DOCUMENTATION](https://cloud.google.com/tasks/docs/)
## Description

Sample command-line program for interacting with the Google Cloud Tasks API.

`tasks.php` is a simple command-line program to demonstrate listing queues,
creating tasks, and pulling and acknowledging tasks.

`src/create_task.php` is a simple function to create pull queue tasks.
Al code in the snippets directory demonstrate how to invoke Cloud Tasks from PHP.

`src/create_task.php` is a simple function to create app engine queue tasks.

## Setup:

Expand All @@ -22,17 +18,45 @@ Sample command-line program for interacting with the Google Cloud Tasks API.

```sh
$ git clone https://github.com/GoogleCloudPlatform/php-docs-samples
$ cd php-docs-samples/tasks
$ cd php-docs-samples/appengine/php72/tasks
```
4. **Install dependencies** via [Composer](http://getcomposer.org/doc/00-intro.md).
Run `php composer.phar install` (if composer is installed locally) or `composer install`
(if composer is installed globally).

## Creating a queue
5. Create a Queue
To create a queue using the Cloud SDK, use the following gcloud command:
```sh
gcloud beta tasks queues create-app-engine-queue my-appengine-queue
```
6. Identify the Location

To create a queue using the Cloud SDK, use the following gcloud command:
Determine the location ID, which can be discovered with
`gcloud alpha tasks queues describe $QUEUE_ID`, with the location embedded in
the "name" value (for instance, if the name is
"projects/my-project/locations/us-central1/queues/my-pull-queue", then the
location is "us-central1").

7. Run `php src/SNIPPET_NAME.php`. The usage will print for each if no arguments are provided:

```
$> php src/create_task.php
Usage: php src/create_task.php PROJECT_ID LOCATION_ID QUEUE_ID [PAYLOAD]
```

## Contributing changes

* See [CONTRIBUTING.md](../../CONTRIBUTING.md)

## Licensing

* See [LICENSE](../../LICENSE)




## Creating a queue

gcloud beta tasks queues create-app-engine-queue my-appengine-queue

## Running the Samples

Expand All @@ -49,14 +73,3 @@ created can be listed with `gcloud alpha tasks queues list`.

export QUEUE_ID=my-appengine-queue

And finally the location ID, which can be discovered with
`gcloud alpha tasks queues describe $QUEUE_ID`, with the location embedded in
the "name" value (for instance, if the name is
"projects/my-project/locations/us-central1/queues/my-pull-queue", then the
location is "us-central1").

export LOCATION_ID=us-central1

Create a task for a queue:

php tasks.php create-task $PROJECT_ID $QUEUE_ID $LOCATION_ID --payload=hello
9 changes: 9 additions & 0 deletions appengine/php72/tasks/snippets/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"require": {
"google/cloud-tasks": "^0.4.1"
},
"require-dev": {
"phpunit/phpunit": "^5",
"google/cloud-tools": "^0.8.5"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2017 Google Inc.
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.
Expand All @@ -25,10 +25,7 @@
</logging>
<filter>
<whitelist>
<file>app.php</file>
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
<php>
<env name="PHPUNIT_TESTS" value="1"/>
</php>
</phpunit>
Loading