Skip to content
Open
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ Google Ad Manager API v202305 is [scheduled to be sunset in May 2024](https://de
* From version 62.0.0, this library requires the minimum PHP version to be
8.0. If you have an older version of PHP, `composer` command will
download an older version of the `googleads/googleads-php-lib` library.
* Guzzle 6, 7, and 8 are supported. Guzzle 8 can only be installed on PHP 8.1
or later, because the `google/auth` releases that allow it require PHP
8.1. On PHP 8.0, Composer will select Guzzle 7.
* This library depends on [Composer](https://getcomposer.org/). If you don't
have it installed on your computer yet, follow the
[installation guide for Linux/Unix/OS X](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx)
Expand Down Expand Up @@ -62,6 +65,10 @@ There are three ways of downloading this library as described below.
* **Our examples are meant to be run from the command line and not as a
webpage.** If you run them as a webpage, results may not be shown
properly.
* The `examples/Auth/GetRefreshToken.php` example requires `react/http`,
which is not compatible with Guzzle 8. To run it, install it with
`composer require --dev --with-all-dependencies react/http:^1.2` and
Composer will select a compatible Guzzle 7 release.

### Using composer require

Expand Down
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
"ext-openssl": "*",
"ext-soap": "*",
"google/auth": "^1.0.0",
"guzzlehttp/guzzle": "^6.0 || ^7.0",
"guzzlehttp/psr7": "^1.7 || ^2.0",
"guzzlehttp/guzzle": "^6.0 || ^7.0 || ^8.0",
"guzzlehttp/promises": "^1.0 || ^2.0 || ^3.0",
"guzzlehttp/psr7": "^1.7 || ^2.0 || ^3.0",
"monolog/monolog": "^2.2.0 || ^3.0",
"phpdocumentor/reflection-docblock": "^3.0.3 || ^4.0 || ^5.0",
"symfony/serializer": "^3.0.3 || ^4.4.0 || ^5.0.0 || ^6.0.0 || ^7.0",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.5.2",
"squizlabs/php_codesniffer": "^2.9 || ^3.2",
"react/http": "^1.2.0"
"squizlabs/php_codesniffer": "^2.9 || ^3.2"
},
"suggest": {
"react/http": "To run the Auth/GetRefreshToken.php example"
Expand Down
12 changes: 5 additions & 7 deletions src/Google/AdsApi/Common/GuzzleLogMessageFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Exception;
use Google\AdsApi\Common\Util\LogMessageScrubbers;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ResponseException;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Psr7\CachingStream;
use GuzzleHttp\Psr7\Message;
Expand Down Expand Up @@ -142,13 +143,10 @@ public function formatDetailed(
$response->withBody(new CachingStream($response->getBody()));

if (!is_null($error)) {
// Creates a new RequestException with the response whose stream
// can be rewound.
$error = RequestException::create(
$request,
$response,
$error
);
// Preserve Guzzle 8 response exception types and error details.
$error = $error instanceof ResponseException
? $error->withResponse($response)
: RequestException::create($request, $response, $error);
}
}

Expand Down
12 changes: 7 additions & 5 deletions src/Google/AdsApi/Common/GuzzleLogMessageHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

namespace Google\AdsApi\Common;

use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\RejectedPromise;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

Expand Down Expand Up @@ -62,10 +64,10 @@ function ($response) use ($request, $logger, $messageFormatter) {
},
function ($reason) use ($request, $logger, $messageFormatter) {
// Logs messages in case of failing HTTP calls.
$response = is_subclass_of(
$reason,
'GuzzleHttp\Exception\RequestException'
) ? $reason->getResponse() : null;
// Guzzle 8 only exposes responses on ResponseException.
$response = $reason instanceof RequestException
&& method_exists($reason, 'getResponse')
? $reason->getResponse() : null;

$logger->warning(
$messageFormatter->formatSummary($request, $response)
Expand All @@ -83,7 +85,7 @@ function ($reason) use ($request, $logger, $messageFormatter) {
));
}

return \GuzzleHttp\Promise\rejection_for($reason);
return new RejectedPromise($reason);
}
);
};
Expand Down
31 changes: 20 additions & 11 deletions tests/Google/AdsApi/Common/GuzzleLogMessageFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ public function testFormatSummary()
'Authorization' => 'Bearer 123.abc.456.xyz',
'developerToken' => 'ABcdeFGH93KL-NOPQ_STUv',
'clientCustomerId' => '111-222-3333',
'skipReportHeader' => false,
'skipColumnHeader' => false,
'skipReportSummary' => false,
'useRawEnumValues' => true,
'includeZeroImpressions' => false
'skipReportHeader' => 'false',
'skipColumnHeader' => 'false',
'skipReportSummary' => 'false',
'useRawEnumValues' => 'true',
'includeZeroImpressions' => 'false'
];
$body = http_build_query([
'__rdquery' => $this->awql,
Expand Down Expand Up @@ -136,11 +136,11 @@ public function testFormatSummary_responseIsNull()
'Authorization' => 'Bearer 123.abc.456.xyz',
'developerToken' => 'ABcdeFGH93KL-NOPQ_STUv',
'clientCustomerId' => '111-222-3333',
'skipReportHeader' => false,
'skipColumnHeader' => false,
'skipReportSummary' => false,
'useRawEnumValues' => true,
'includeZeroImpressions' => false
'skipReportHeader' => 'false',
'skipColumnHeader' => 'false',
'skipReportSummary' => 'false',
'useRawEnumValues' => 'true',
'includeZeroImpressions' => 'false'
];
$body = http_build_query([
'__rdquery' => $this->awql,
Expand Down Expand Up @@ -437,7 +437,16 @@ public function testFormatDetailed_logReportData_withErrors()
Utils::streamFor($this->reportDownloadError)
)
);
$error = new ClientException('Client error: 400', $request, $response);
// The message Guzzle generates for this response, which Guzzle 8 keeps as is.
$error = new ClientException(
'Client error: `POST /api/adwords/reportdownload/v201809` resulted'
. " in a `400 Bad Request` response:\n"
. '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<reportDownloadError><ApiError><type>ReportDefinitionError.INVALI'
. ' (truncated...)',
$request,
$response
);
$guzzleLogMessageFormatter = new GuzzleLogMessageFormatter(
['Authorization', 'developerToken'],
[],
Expand Down
192 changes: 192 additions & 0 deletions tests/Google/AdsApi/Common/GuzzleLogMessageHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
<?php
/**
* Copyright 2026 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.
*/

namespace Google\AdsApi\Common;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ResponseTransferException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\NoSeekStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Utils;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Throwable;

/**
* Unit tests for `GuzzleLogMessageHandler`.
*
* @see GuzzleLogMessageHandler
* @small
*/
class GuzzleLogMessageHandlerTest extends TestCase
{

/**
* @covers \Google\AdsApi\Common\GuzzleLogMessageHandler::log
* @dataProvider provideShouldLogResponsePayload
*/
public function testLogsSuccessfulCall($shouldLogResponsePayload)
{
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('info')
->with($this->stringContains('Status: 200'));
$logger->expects($this->once())->method('debug')
->with($this->logicalAnd(
$this->stringContains('Authorization: REDACTED'),
$this->stringContains(
$shouldLogResponsePayload ? 'report data' : 'REDACTED DATA'
)
));
$logger->expects($this->never())->method('warning');
$client = $this->createClient(
[new Response(200, [], new NoSeekStream(Utils::streamFor('report data')))],
$logger,
$shouldLogResponsePayload
);

$response = $client->request('GET', 'https://example.com/report', [
'headers' => ['Authorization' => 'Bearer secret-token']
]);

// The response body must still be readable after it was logged.
$this->assertSame('report data', $response->getBody()->getContents());
}

public function provideShouldLogResponsePayload()
{
return [[true], [false]];
}

/**
* @covers \Google\AdsApi\Common\GuzzleLogMessageHandler::log
* @dataProvider provideFailures
*/
public function testLogsFailedCallAndRethrows(Throwable $reason, $expectedStatus)
{
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('warning')
->with($this->stringContains('Status: ' . $expectedStatus));
$logger->expects($this->once())->method('notice')
->with($this->stringContains($reason->getMessage()));
$logger->expects($this->never())->method('info');
$client = $this->createClient([$reason], $logger, false);

$this->expectExceptionObject($reason);
$client->request('GET', 'https://example.com/report');
}

public function provideFailures()
{
$request = new Request('GET', 'https://example.com/report');
$failures = [
[new RequestException('Request failed', $request), 'NULL'],
[new ConnectException('Connection failed', $request), 'NULL'],
[new ClientException('Forbidden', $request, new Response(403)), '403'],
[new RuntimeException('Handler failed'), 'NULL']
];
// Guzzle 8 reports failures that happen after the response headers
// were received with a dedicated exception type.
if (class_exists(ResponseTransferException::class)) {
$failures[] = [
new ResponseTransferException('Transfer failed', $request, new Response(200)),
'200'
];
}
return $failures;
}

/**
* @covers \Google\AdsApi\Common\GuzzleLogMessageHandler::log
* @dataProvider provideShouldLogResponsePayload
*/
public function testErrorResponseRemainsReadable($shouldLogResponsePayload)
{
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('notice')
->with($this->stringContains(
$shouldLogResponsePayload ? 'failure details' : 'REDACTED DATA'
));
$client = $this->createClient(
[new Response(403, [], new NoSeekStream(Utils::streamFor('failure details')))],
$logger,
$shouldLogResponsePayload
);

try {
$client->request('GET', 'https://example.com/report');
$this->fail('Expected a ClientException.');
} catch (ClientException $error) {
$this->assertSame(
'failure details',
$error->getResponse()->getBody()->getContents()
);
}
}

/**
* @covers \Google\AdsApi\Common\GuzzleLogMessageHandler::log
*/
public function testTransferFailureKeepsItsTypeAndResponse()
{
if (!class_exists(ResponseTransferException::class)) {
$this->markTestSkipped('ResponseTransferException only exists in Guzzle 8.');
}
$request = new Request('GET', 'https://example.com/report');
$response = new Response(200, [], new NoSeekStream(Utils::streamFor('partial report')));
$previous = new RuntimeException('Connection reset');
$reason = new ResponseTransferException('Transfer failed', $request, $response, $previous);
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())->method('notice')
->with($this->logicalAnd(
$this->stringContains('Transfer failed'),
$this->stringContains('partial report')
));
$client = $this->createClient([$reason], $logger, true);

try {
$client->request('GET', 'https://example.com/report');
$this->fail('Expected a ResponseTransferException.');
} catch (ResponseTransferException $error) {
$this->assertSame('Transfer failed', $error->getMessage());
$this->assertSame($previous, $error->getPrevious());
$this->assertSame(
'partial report',
$error->getResponse()->getBody()->getContents()
);
}
}

private function createClient(
array $queue,
LoggerInterface $logger,
$shouldLogResponsePayload
) {
$client = new Client(['handler' => HandlerStack::create(new MockHandler($queue))]);
return (new AdsGuzzleHttpClientFactory(
$logger,
new GuzzleLogMessageFormatter(['Authorization'], [], $shouldLogResponsePayload),
$client
))->generateHttpClient();
}
}
Loading