From fe367bf30631a470be738370bc3cbcab9fff7c02 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Tue, 16 Jun 2026 11:53:15 -0700 Subject: [PATCH 01/15] chore(gax): upgrade to google/longrunning:v1, remove deprecated classes and methods --- Gax/composer.json | 2 +- Gax/src/AgentHeader.php | 4 +- Gax/src/ApiException.php | 2 + Gax/src/ApiKeyHeaderCredentials.php | 2 + Gax/src/ApiStatus.php | 2 + Gax/src/ArrayTrait.php | 2 + Gax/src/BidiStream.php | 2 + Gax/src/Call.php | 2 + Gax/src/ClientOptionsTrait.php | 2 + Gax/src/ClientStream.php | 2 + Gax/src/CredentialsWrapper.php | 20 +----- Gax/src/FixedSizeCollection.php | 2 + Gax/src/GPBLabel.php | 2 + Gax/src/GPBType.php | 2 + Gax/src/GapicClientTrait.php | 4 +- Gax/src/GrpcSupportTrait.php | 2 + Gax/src/HeaderCredentialsInterface.php | 2 + Gax/src/InsecureCredentialsWrapper.php | 2 + Gax/src/InsecureRequestBuilder.php | 1 + Gax/src/KnownTypes.php | 7 +- .../CredentialsWrapperMiddleware.php | 2 + Gax/src/Middleware/FixedHeaderMiddleware.php | 2 + Gax/src/Middleware/MiddlewareInterface.php | 2 + Gax/src/Middleware/OperationsMiddleware.php | 2 + .../Middleware/OptionsFilterMiddleware.php | 2 + Gax/src/Middleware/PagedMiddleware.php | 2 + .../RequestAutoPopulationMiddleware.php | 2 + .../Middleware/ResponseMetadataMiddleware.php | 2 + Gax/src/Middleware/RetryMiddleware.php | 6 +- .../Middleware/TransportCallMiddleware.php | 2 + Gax/src/OperationResponse.php | 2 + Gax/src/Options/CallOptions.php | 12 +--- Gax/src/Options/ClientOptions.php | 2 + Gax/src/Options/OptionsInterface.php | 2 + Gax/src/Options/OptionsTrait.php | 2 + Gax/src/Options/TransportOptions.php | 2 + .../GrpcFallbackTransportOptions.php | 2 + .../TransportOptions/GrpcTransportOptions.php | 15 ++-- .../TransportOptions/RestTransportOptions.php | 2 + Gax/src/Page.php | 2 + Gax/src/PageStreamingDescriptor.php | 2 + Gax/src/PagedListResponse.php | 2 + Gax/src/PathTemplate.php | 2 + Gax/src/PollingTrait.php | 4 +- Gax/src/RequestBuilder.php | 2 + Gax/src/RequestParamsHeaderDescriptor.php | 2 + Gax/src/ResourceHelperTrait.php | 2 + .../AbsoluteResourceTemplate.php | 2 + Gax/src/ResourceTemplate/Parser.php | 2 + .../RelativeResourceTemplate.php | 6 +- .../ResourceTemplateInterface.php | 2 + Gax/src/ResourceTemplate/Segment.php | 2 + Gax/src/RetrySettings.php | 2 + Gax/src/Serializer.php | 4 +- Gax/src/ServerStream.php | 2 + Gax/src/ServerStreamingCallInterface.php | 2 + Gax/src/ServiceAddressTrait.php | 64 ----------------- Gax/src/Testing/GeneratedTest.php | 2 + .../Testing/MessageAwareArrayComparator.php | 2 + Gax/src/Testing/MessageAwareExporter.php | 2 + Gax/src/Testing/MockBidiStreamingCall.php | 2 + Gax/src/Testing/MockClientStreamingCall.php | 2 + Gax/src/Testing/MockGrpcTransport.php | 2 + Gax/src/Testing/MockServerStreamingCall.php | 2 + Gax/src/Testing/MockStatus.php | 2 + Gax/src/Testing/MockStubTrait.php | 2 + Gax/src/Testing/MockTransport.php | 2 + Gax/src/Testing/MockUnaryCall.php | 2 + .../Testing/ProtobufGPBEmptyComparator.php | 2 + Gax/src/Testing/ProtobufMessageComparator.php | 2 + Gax/src/Testing/ReceivedRequest.php | 2 + Gax/src/Testing/SerializationTrait.php | 2 + Gax/src/Transport/Grpc/ForwardingCall.php | 2 + .../Grpc/ForwardingServerStreamingCall.php | 2 + .../Transport/Grpc/ForwardingUnaryCall.php | 2 + .../Grpc/ServerStreamingCallWrapper.php | 2 + .../Grpc/UnaryInterceptorInterface.php | 61 ---------------- Gax/src/Transport/GrpcFallbackTransport.php | 8 ++- Gax/src/Transport/GrpcTransport.php | 25 ++----- Gax/src/Transport/HttpUnaryTransportTrait.php | 2 + Gax/src/Transport/Rest/JsonStreamDecoder.php | 2 + .../Rest/RestServerStreamingCall.php | 2 + Gax/src/Transport/RestTransport.php | 8 ++- Gax/src/Transport/TransportInterface.php | 2 + Gax/src/UriTrait.php | 2 + Gax/src/ValidationException.php | 2 + Gax/src/ValidationTrait.php | 2 + Gax/src/Version.php | 2 + .../src/V1beta1/Client/ComplianceClient.php | 2 + .../src/V1beta1/Client/EchoClient.php | 2 + .../src/V1beta1/Client/IdentityClient.php | 2 + .../src/V1beta1/Client/MessagingClient.php | 2 + .../V1beta1/Client/SequenceServiceClient.php | 2 + .../src/V1beta1/Client/TestingClient.php | 2 + .../compliance_descriptor_config.php | 2 + .../compliance_rest_client_config.php | 2 + .../resources/echo_descriptor_config.php | 2 + .../resources/echo_rest_client_config.php | 2 + .../resources/identity_descriptor_config.php | 2 + .../resources/identity_rest_client_config.php | 2 + .../resources/messaging_descriptor_config.php | 2 + .../messaging_rest_client_config.php | 2 + .../sequence_service_descriptor_config.php | 2 + .../sequence_service_rest_client_config.php | 2 + .../resources/testing_descriptor_config.php | 2 + .../resources/testing_rest_client_config.php | 2 + Gax/tests/Unit/CredentialsWrapperTest.php | 61 ---------------- Gax/tests/Unit/GapicClientTraitTest.php | 18 ++--- .../Middleware/OperationsMiddlewareTest.php | 10 +-- Gax/tests/Unit/ServiceAddressTraitTest.php | 69 ------------------- .../testdata/mocks/src/GapicClientStub.php | 2 + 111 files changed, 244 insertions(+), 345 deletions(-) delete mode 100644 Gax/src/ServiceAddressTrait.php delete mode 100644 Gax/src/Transport/Grpc/UnaryInterceptorInterface.php delete mode 100644 Gax/tests/Unit/ServiceAddressTraitTest.php diff --git a/Gax/composer.json b/Gax/composer.json index f6869faa4e29..70d5eb81d15a 100644 --- a/Gax/composer.json +++ b/Gax/composer.json @@ -14,7 +14,7 @@ "guzzlehttp/promises": "^2.0", "guzzlehttp/psr7": "^2.0", "google/common-protos": "^4.4", - "google/longrunning": "~0.4", + "google/longrunning": "~0.4||^1.0", "ramsey/uuid": "^4.0" }, "require-dev": { diff --git a/Gax/src/AgentHeader.php b/Gax/src/AgentHeader.php index 4fda2b0e9a98..4754a9752fff 100644 --- a/Gax/src/AgentHeader.php +++ b/Gax/src/AgentHeader.php @@ -1,4 +1,6 @@ credentialsFetcher->getLastReceivedToken(); - if (self::isExpired($token)) { - $this->checkUniverseDomain(); - - $token = $this->credentialsFetcher->fetchAuthToken($this->authHttpHandler); - if (!self::isValid($token)) { - return ''; - } - } - return empty($token['access_token']) ? '' : 'Bearer ' . $token['access_token']; - } - /** * @param string $audience optional audience for self-signed JWTs. * @return callable Callable function that returns an authorization header. diff --git a/Gax/src/FixedSizeCollection.php b/Gax/src/FixedSizeCollection.php index 03ec835c1368..13d4f3219cc2 100644 --- a/Gax/src/FixedSizeCollection.php +++ b/Gax/src/FixedSizeCollection.php @@ -1,4 +1,6 @@ \Google\Rpc\RetryInfo::class, 'google.rpc.debuginfo-bin' => \Google\Rpc\DebugInfo::class, diff --git a/Gax/src/Middleware/CredentialsWrapperMiddleware.php b/Gax/src/Middleware/CredentialsWrapperMiddleware.php index 086df0ef0252..e406e77662a9 100644 --- a/Gax/src/Middleware/CredentialsWrapperMiddleware.php +++ b/Gax/src/Middleware/CredentialsWrapperMiddleware.php @@ -1,4 +1,6 @@ retrySettings->getMaxRpcTimeoutMillis(); $totalTimeoutMs = $this->retrySettings->getTotalTimeoutMillis(); - $delayMs = $this->retrySettings->getInitialRetryDelayMillis(); + $delayMs = (int) $this->retrySettings->getInitialRetryDelayMillis(); $timeoutMs = $options['timeoutMillis']; $currentTimeMs = $this->getCurrentTimeMs(); $deadlineMs = $this->deadlineMs ?: $currentTimeMs + $totalTimeoutMs; @@ -180,7 +182,7 @@ private function retry(Call $call, array $options, string $status) ); } - protected function getCurrentTimeMs() + protected function getCurrentTimeMs(): float { return microtime(true) * 1000.0; } diff --git a/Gax/src/Middleware/TransportCallMiddleware.php b/Gax/src/Middleware/TransportCallMiddleware.php index 1306f78e11d0..dfd68cc121db 100644 --- a/Gax/src/Middleware/TransportCallMiddleware.php +++ b/Gax/src/Middleware/TransportCallMiddleware.php @@ -1,4 +1,6 @@ setTransportOptions($transportSpecificOptions); - - return $this; - } - /** * @param RetrySettings|array|null $retrySettings * diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index b9677fe20399..994bbc81b884 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -1,4 +1,6 @@ getCurrentTimeMillis() > $endTime) { return false; } - $this->sleepMillis($currentPollDelayMillis); + $this->sleepMillis((int) $currentPollDelayMillis); if ($pollCallable()) { return true; } diff --git a/Gax/src/RequestBuilder.php b/Gax/src/RequestBuilder.php index 330d13dd4239..179c48d9e3b9 100644 --- a/Gax/src/RequestBuilder.php +++ b/Gax/src/RequestBuilder.php @@ -1,4 +1,6 @@ renderingException($bindings, "missing required binding '$key' for segment '$segment'"); } $value = $bindings[$key]; - if (!is_null($value) && $segment->matches($value)) { + if (!is_null($value) && $segment->matches((string) $value)) { $literalSegments[] = new Segment( Segment::LITERAL_SEGMENT, - $value, + (string) $value, $segment->getValue(), $segment->getTemplate(), $segment->getSeparator() diff --git a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php index ffa3c8138da5..d5cb1357f519 100644 --- a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php +++ b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php @@ -1,4 +1,6 @@ $values) { foreach ($values as $value) { $decodedValue = ['@type' => $key]; - if (self::hasBinaryHeaderSuffix($key)) { + if (is_string($key) && self::hasBinaryHeaderSuffix($key)) { if (isset(KnownTypes::BIN_TYPES[$key])) { $class = KnownTypes::BIN_TYPES[$key]; /** diff --git a/Gax/src/ServerStream.php b/Gax/src/ServerStream.php index 3257e65504fa..c659041c5584 100644 --- a/Gax/src/ServerStream.php +++ b/Gax/src/ServerStream.php @@ -1,4 +1,6 @@ null, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $httpHandler = $config['httpHandler'] ?: self::buildHttpHandlerAsync(logger: $config['logger']); $transport = new GrpcFallbackTransport("$baseUri:$port", $httpHandler); if ($config['clientCertSource']) { diff --git a/Gax/src/Transport/GrpcTransport.php b/Gax/src/Transport/GrpcTransport.php index 5fd03a6fe52d..1881335467f7 100644 --- a/Gax/src/Transport/GrpcTransport.php +++ b/Gax/src/Transport/GrpcTransport.php @@ -1,4 +1,6 @@ null, 'logger' => null, ]; - list($addr, $port) = self::normalizeServiceAddress($apiEndpoint); + list($addr, $port) = self::normalizeApiEndpoint($apiEndpoint); $host = "$addr:$port"; $stubOpts = $config['stubOpts']; // Set the required 'credentials' key in stubOpts if it is not already set. Use diff --git a/Gax/src/Transport/HttpUnaryTransportTrait.php b/Gax/src/Transport/HttpUnaryTransportTrait.php index 38c4ca1f5522..8a9b3bea16b7 100644 --- a/Gax/src/Transport/HttpUnaryTransportTrait.php +++ b/Gax/src/Transport/HttpUnaryTransportTrait.php @@ -1,4 +1,6 @@ false, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $requestBuilder = $config['hasEmulator'] ? new InsecureRequestBuilder("$baseUri:$port", $restConfigPath) : new RequestBuilder("$baseUri:$port", $restConfigPath); diff --git a/Gax/src/Transport/TransportInterface.php b/Gax/src/Transport/TransportInterface.php index 682a4301989c..8ae6d918c590 100644 --- a/Gax/src/Transport/TransportInterface.php +++ b/Gax/src/Transport/TransportInterface.php @@ -1,4 +1,6 @@ getAuthorizationHeaderCallback()(); } - /** - * Same test as above, but calls the deprecated CredentialsWrapper::getBearerString method - * instead of CredentialsWrapper::getAuthorizationHeaderCallback - * @dataProvider provideCheckUniverseDomainFails - */ - public function testCheckUniverseDomainOnGetBearerStringFails( - ?string $universeDomain, - ?string $credentialsUniverse, - ?string $message = null - ) { - $this->expectException(ValidationException::class); - $this->expectExceptionMessage($message ?: sprintf( - 'The configured universe domain (%s) does not match the credential universe domain (%s)', - is_null($universeDomain) ? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN : $universeDomain, - is_null($credentialsUniverse) ? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN : $credentialsUniverse, - )); - $fetcher = $this->prophesize(FetchAuthTokenInterface::class); - // When the $credentialsUniverse is null, the fetcher doesn't implement GetUniverseDomainInterface - if (!is_null($credentialsUniverse)) { - $fetcher->willImplement(GetUniverseDomainInterface::class); - $fetcher->getUniverseDomain()->willReturn($credentialsUniverse); - } - $fetcher->getLastReceivedToken()->willReturn(null); - // When $universeDomain is null, it means no $universeDomain argument was provided - if (is_null($universeDomain)) { - $credentialsWrapper = new CredentialsWrapper($fetcher->reveal()); - } else { - $credentialsWrapper = new CredentialsWrapper($fetcher->reveal(), null, $universeDomain); - } - // Check getBearerString (deprecated) - $credentialsWrapper->getBearerString(); - } - public function provideCheckUniverseDomainFails() { return [ @@ -314,11 +281,6 @@ public function testCheckUniverseDomainPasses(?string $universeDomain, ?string $ ['authorization' => ['Bearer abc']], $credentialsWrapper->getAuthorizationHeaderCallback()() ); - // Check getBearerString (deprecated) - $this->assertEquals( - 'Bearer abc', - $credentialsWrapper->getBearerString() - ); } public function provideCheckUniverseDomainPasses() @@ -344,29 +306,6 @@ public function testCheckUniverseDomainOnGceCredentialsDoesNotCheck() $credentialsWrapper->checkUniverseDomain(); } - /** - * @dataProvider getBearerStringData - * @runInSeparateProcess - */ - public function testGetBearerString(string $fetcherFunc, $expectedBearerString) - { - $fetcher = $this->$fetcherFunc(); - $credentialsWrapper = new CredentialsWrapper($fetcher); - $bearerString = $credentialsWrapper->getBearerString(); - $this->assertSame($expectedBearerString, $bearerString); - } - - public function getBearerStringData() - { - return [ - ['getExpiredFetcher', 'Bearer 456'], - ['getEagerExpiredFetcher', 'Bearer 456'], - ['getUnexpiredFetcher', 'Bearer 123'], - ['getInsecureFetcher', ''], - ['getNullFetcher', ''], - ]; - } - /** * @dataProvider getAuthorizationHeaderCallbackData * @runInSeparateProcess diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index fef2951d4197..06c7b3fb58a1 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1581,17 +1581,17 @@ public function __invoke(Call $call, array $options) $transport->startUnaryCall( Argument::type(Call::class), [ - 'transportOptions' => [ - 'custom' => ['addModifyUnaryCallableOption' => true] - ], - 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'transportOptions' => [ + 'custom' => ['addModifyUnaryCallableOption' => true] + ], + 'headers' => AgentHeader::buildAgentHeader([]), + 'credentialsWrapper' => CredentialsWrapper::build([ + 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' + ]) ] ) - ->shouldBeCalledOnce() - ->willReturn(new FulfilledPromise(new Operation())); + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise(new Operation())); $client->startCall( 'simpleMethod', diff --git a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php index 7d7dac94189e..1c264ae76ee9 100644 --- a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php @@ -33,9 +33,9 @@ namespace Google\ApiCore\Tests\Unit\Middleware; use Google\ApiCore\Call; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\ApiCore\Middleware\OperationsMiddleware; -use Google\ApiCore\Testing\MockResponse; +use Google\ApiCore\Testing\MockRequest; use GuzzleHttp\Promise\Promise; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; @@ -50,11 +50,11 @@ public function testOperationNameMethodDescriptor() $operationsClient = $this->prophesize(OperationsClient::class); $descriptor = [ - 'operationNameMethod' => 'getNumber' + 'operationNameMethod' => 'getPageToken' ]; $handler = function (Call $call, $options) use (&$callCount) { return $promise = new Promise(function () use (&$promise) { - $response = new MockResponse(['number' => 123]); + $response = new MockRequest(['page_token' => 'abc']); $promise->resolve($response); }); }; @@ -64,6 +64,6 @@ public function testOperationNameMethodDescriptor() [] )->wait(); - $this->assertEquals(123, $response->getName()); + $this->assertEquals('abc', $response->getName()); } } diff --git a/Gax/tests/Unit/ServiceAddressTraitTest.php b/Gax/tests/Unit/ServiceAddressTraitTest.php deleted file mode 100644 index ba5cf81c7a64..000000000000 --- a/Gax/tests/Unit/ServiceAddressTraitTest.php +++ /dev/null @@ -1,69 +0,0 @@ -assertSame($expectedAddress, $actualAddress); - $this->assertSame($expectedPort, $actualPort); - } - - public function normalizeServiceAddressData() - { - return [ - ['simple.com:123', 'simple.com', '123'], - ['really.long.and.dotted:456', 'really.long.and.dotted', '456'], - ['noport.com', 'noport.com', self::$defaultPort], - ]; - } - - /** - * @dataProvider normalizeServiceAddressInvalidData - */ - public function testNormalizeServiceAddressInvalid($serviceAddressString) - { - $this->expectException(ValidationException::class); - $this->expectExceptionMessage('Invalid apiEndpoint'); - - self::normalizeServiceAddress($serviceAddressString); - } - - public function normalizeServiceAddressInvalidData() - { - return [ - ['too.many:colons:123'], - ['too:many:colons'], - ]; - } -} diff --git a/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php b/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php index d5a022de7c78..4520de072c76 100644 --- a/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php +++ b/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php @@ -1,4 +1,6 @@ Date: Tue, 16 Jun 2026 12:49:40 -0700 Subject: [PATCH 02/15] add new ApiEndpoint trait --- Gax/src/ApiEndpointTrait.php | 62 +++++++++++++++++++++++ Gax/tests/Unit/ApiEndpointTraitTest.php | 65 +++++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 Gax/src/ApiEndpointTrait.php create mode 100644 Gax/tests/Unit/ApiEndpointTraitTest.php diff --git a/Gax/src/ApiEndpointTrait.php b/Gax/src/ApiEndpointTrait.php new file mode 100644 index 000000000000..df74fed5ccba --- /dev/null +++ b/Gax/src/ApiEndpointTrait.php @@ -0,0 +1,62 @@ +assertSame($expectedAddress, $actualAddress); + $this->assertSame($expectedPort, $actualPort); + } + + public function normalizeApiEndpointData() + { + return [ + ['simple.com:123', 'simple.com', '123'], + ['really.long.and.dotted:456', 'really.long.and.dotted', '456'], + ['noport.com', 'noport.com', self::$defaultPort], + ]; + } + + /** + * @dataProvider normalizeApiEndpointInvalidData + */ + public function testNormalizeApiEndpointInvalid($ApiEndpointString) + { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('Invalid apiEndpoint'); + + self::normalizeApiEndpoint($ApiEndpointString); + } + + public function normalizeApiEndpointInvalidData() + { + return [ + ['too.many:colons:123'], + ['too:many:colons'], + ]; + } +} From 1b318b6d6604cadfa541113deda8b8bfb51a4869 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Tue, 16 Jun 2026 11:53:15 -0700 Subject: [PATCH 03/15] chore(gax): upgrade to google/longrunning:v1, remove deprecated classes and methods --- Gax/composer.json | 2 +- Gax/src/AgentHeader.php | 4 +- Gax/src/ApiException.php | 2 + Gax/src/ApiKeyHeaderCredentials.php | 2 + Gax/src/ApiStatus.php | 2 + Gax/src/ArrayTrait.php | 2 + Gax/src/BidiStream.php | 2 + Gax/src/Call.php | 2 + Gax/src/ClientOptionsTrait.php | 2 + Gax/src/ClientStream.php | 2 + Gax/src/CredentialsWrapper.php | 20 +----- Gax/src/FixedSizeCollection.php | 2 + Gax/src/GPBLabel.php | 2 + Gax/src/GPBType.php | 2 + Gax/src/GapicClientTrait.php | 4 +- Gax/src/GrpcSupportTrait.php | 2 + Gax/src/HeaderCredentialsInterface.php | 2 + Gax/src/InsecureCredentialsWrapper.php | 2 + Gax/src/InsecureRequestBuilder.php | 1 + Gax/src/KnownTypes.php | 7 +- .../CredentialsWrapperMiddleware.php | 2 + Gax/src/Middleware/FixedHeaderMiddleware.php | 2 + Gax/src/Middleware/MiddlewareInterface.php | 2 + Gax/src/Middleware/OperationsMiddleware.php | 2 + .../Middleware/OptionsFilterMiddleware.php | 2 + Gax/src/Middleware/PagedMiddleware.php | 2 + .../RequestAutoPopulationMiddleware.php | 2 + .../Middleware/ResponseMetadataMiddleware.php | 2 + Gax/src/Middleware/RetryMiddleware.php | 6 +- .../Middleware/TransportCallMiddleware.php | 2 + Gax/src/OperationResponse.php | 2 + Gax/src/Options/CallOptions.php | 12 +--- Gax/src/Options/ClientOptions.php | 2 + Gax/src/Options/OptionsInterface.php | 2 + Gax/src/Options/OptionsTrait.php | 2 + Gax/src/Options/TransportOptions.php | 2 + .../GrpcFallbackTransportOptions.php | 2 + .../TransportOptions/GrpcTransportOptions.php | 15 ++-- .../TransportOptions/RestTransportOptions.php | 2 + Gax/src/Page.php | 2 + Gax/src/PageStreamingDescriptor.php | 2 + Gax/src/PagedListResponse.php | 2 + Gax/src/PathTemplate.php | 2 + Gax/src/PollingTrait.php | 4 +- Gax/src/RequestBuilder.php | 2 + Gax/src/RequestParamsHeaderDescriptor.php | 2 + Gax/src/ResourceHelperTrait.php | 2 + .../AbsoluteResourceTemplate.php | 2 + Gax/src/ResourceTemplate/Parser.php | 2 + .../RelativeResourceTemplate.php | 6 +- .../ResourceTemplateInterface.php | 2 + Gax/src/ResourceTemplate/Segment.php | 2 + Gax/src/RetrySettings.php | 2 + Gax/src/Serializer.php | 4 +- Gax/src/ServerStream.php | 2 + Gax/src/ServerStreamingCallInterface.php | 2 + Gax/src/ServiceAddressTrait.php | 64 ----------------- Gax/src/Testing/GeneratedTest.php | 2 + .../Testing/MessageAwareArrayComparator.php | 2 + Gax/src/Testing/MessageAwareExporter.php | 2 + Gax/src/Testing/MockBidiStreamingCall.php | 2 + Gax/src/Testing/MockClientStreamingCall.php | 2 + Gax/src/Testing/MockGrpcTransport.php | 2 + Gax/src/Testing/MockServerStreamingCall.php | 2 + Gax/src/Testing/MockStatus.php | 2 + Gax/src/Testing/MockStubTrait.php | 2 + Gax/src/Testing/MockTransport.php | 2 + Gax/src/Testing/MockUnaryCall.php | 2 + .../Testing/ProtobufGPBEmptyComparator.php | 2 + Gax/src/Testing/ProtobufMessageComparator.php | 2 + Gax/src/Testing/ReceivedRequest.php | 2 + Gax/src/Testing/SerializationTrait.php | 2 + Gax/src/Transport/Grpc/ForwardingCall.php | 2 + .../Grpc/ForwardingServerStreamingCall.php | 2 + .../Transport/Grpc/ForwardingUnaryCall.php | 2 + .../Grpc/ServerStreamingCallWrapper.php | 2 + .../Grpc/UnaryInterceptorInterface.php | 61 ---------------- Gax/src/Transport/GrpcFallbackTransport.php | 8 ++- Gax/src/Transport/GrpcTransport.php | 25 ++----- Gax/src/Transport/HttpUnaryTransportTrait.php | 2 + Gax/src/Transport/Rest/JsonStreamDecoder.php | 2 + .../Rest/RestServerStreamingCall.php | 2 + Gax/src/Transport/RestTransport.php | 8 ++- Gax/src/Transport/TransportInterface.php | 2 + Gax/src/UriTrait.php | 2 + Gax/src/ValidationException.php | 2 + Gax/src/ValidationTrait.php | 2 + Gax/src/Version.php | 2 + .../src/V1beta1/Client/ComplianceClient.php | 2 + .../src/V1beta1/Client/EchoClient.php | 2 + .../src/V1beta1/Client/IdentityClient.php | 2 + .../src/V1beta1/Client/MessagingClient.php | 2 + .../V1beta1/Client/SequenceServiceClient.php | 2 + .../src/V1beta1/Client/TestingClient.php | 2 + .../compliance_descriptor_config.php | 2 + .../compliance_rest_client_config.php | 2 + .../resources/echo_descriptor_config.php | 2 + .../resources/echo_rest_client_config.php | 2 + .../resources/identity_descriptor_config.php | 2 + .../resources/identity_rest_client_config.php | 2 + .../resources/messaging_descriptor_config.php | 2 + .../messaging_rest_client_config.php | 2 + .../sequence_service_descriptor_config.php | 2 + .../sequence_service_rest_client_config.php | 2 + .../resources/testing_descriptor_config.php | 2 + .../resources/testing_rest_client_config.php | 2 + Gax/tests/Unit/CredentialsWrapperTest.php | 61 ---------------- Gax/tests/Unit/GapicClientTraitTest.php | 18 ++--- .../Middleware/OperationsMiddlewareTest.php | 10 +-- Gax/tests/Unit/ServiceAddressTraitTest.php | 69 ------------------- .../testdata/mocks/src/GapicClientStub.php | 2 + 111 files changed, 244 insertions(+), 345 deletions(-) delete mode 100644 Gax/src/ServiceAddressTrait.php delete mode 100644 Gax/src/Transport/Grpc/UnaryInterceptorInterface.php delete mode 100644 Gax/tests/Unit/ServiceAddressTraitTest.php diff --git a/Gax/composer.json b/Gax/composer.json index bd5af2ac073e..7b14e5bf4a96 100644 --- a/Gax/composer.json +++ b/Gax/composer.json @@ -16,7 +16,7 @@ "guzzlehttp/promises": "^2.0", "guzzlehttp/psr7": "^2.0", "google/common-protos": "^4.4", - "google/longrunning": "~0.4", + "google/longrunning": "~0.4||^1.0", "ramsey/uuid": "^4.0" }, "require-dev": { diff --git a/Gax/src/AgentHeader.php b/Gax/src/AgentHeader.php index 4fda2b0e9a98..4754a9752fff 100644 --- a/Gax/src/AgentHeader.php +++ b/Gax/src/AgentHeader.php @@ -1,4 +1,6 @@ credentialsFetcher->getLastReceivedToken(); - if (self::isExpired($token)) { - $this->checkUniverseDomain(); - - $token = $this->credentialsFetcher->fetchAuthToken($this->authHttpHandler); - if (!self::isValid($token)) { - return ''; - } - } - return empty($token['access_token']) ? '' : 'Bearer ' . $token['access_token']; - } - /** * @param string $audience optional audience for self-signed JWTs. * @return callable Callable function that returns an authorization header. diff --git a/Gax/src/FixedSizeCollection.php b/Gax/src/FixedSizeCollection.php index 03ec835c1368..13d4f3219cc2 100644 --- a/Gax/src/FixedSizeCollection.php +++ b/Gax/src/FixedSizeCollection.php @@ -1,4 +1,6 @@ \Google\Rpc\RetryInfo::class, 'google.rpc.debuginfo-bin' => \Google\Rpc\DebugInfo::class, diff --git a/Gax/src/Middleware/CredentialsWrapperMiddleware.php b/Gax/src/Middleware/CredentialsWrapperMiddleware.php index 086df0ef0252..e406e77662a9 100644 --- a/Gax/src/Middleware/CredentialsWrapperMiddleware.php +++ b/Gax/src/Middleware/CredentialsWrapperMiddleware.php @@ -1,4 +1,6 @@ retrySettings->getRpcTimeoutMultiplier(); $maxTimeoutMs = $this->retrySettings->getMaxRpcTimeoutMillis(); - $delayMs = $this->retrySettings->getInitialRetryDelayMillis(); + $delayMs = (int) $this->retrySettings->getInitialRetryDelayMillis(); $timeoutMs = $options['timeoutMillis']; $currentTimeMs = $this->getCurrentTimeMs(); @@ -183,7 +185,7 @@ private function retry(Call $call, array $options, string $status) ); } - protected function getCurrentTimeMs() + protected function getCurrentTimeMs(): float { return microtime(true) * 1000.0; } diff --git a/Gax/src/Middleware/TransportCallMiddleware.php b/Gax/src/Middleware/TransportCallMiddleware.php index 1306f78e11d0..dfd68cc121db 100644 --- a/Gax/src/Middleware/TransportCallMiddleware.php +++ b/Gax/src/Middleware/TransportCallMiddleware.php @@ -1,4 +1,6 @@ setTransportOptions($transportSpecificOptions); - - return $this; - } - /** * @param RetrySettings|array|null $retrySettings * diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index b9677fe20399..994bbc81b884 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -1,4 +1,6 @@ getCurrentTimeMillis() > $endTime) { return false; } - $this->sleepMillis($currentPollDelayMillis); + $this->sleepMillis((int) $currentPollDelayMillis); if ($pollCallable()) { return true; } diff --git a/Gax/src/RequestBuilder.php b/Gax/src/RequestBuilder.php index 330d13dd4239..179c48d9e3b9 100644 --- a/Gax/src/RequestBuilder.php +++ b/Gax/src/RequestBuilder.php @@ -1,4 +1,6 @@ renderingException($bindings, "missing required binding '$key' for segment '$segment'"); } $value = $bindings[$key]; - if (!is_null($value) && $segment->matches($value)) { + if (!is_null($value) && $segment->matches((string) $value)) { $literalSegments[] = new Segment( Segment::LITERAL_SEGMENT, - $value, + (string) $value, $segment->getValue(), $segment->getTemplate(), $segment->getSeparator() diff --git a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php index ffa3c8138da5..d5cb1357f519 100644 --- a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php +++ b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php @@ -1,4 +1,6 @@ $values) { foreach ($values as $value) { $decodedValue = ['@type' => $key]; - if (self::hasBinaryHeaderSuffix($key)) { + if (is_string($key) && self::hasBinaryHeaderSuffix($key)) { if (isset(KnownTypes::BIN_TYPES[$key])) { $class = KnownTypes::BIN_TYPES[$key]; /** diff --git a/Gax/src/ServerStream.php b/Gax/src/ServerStream.php index 3257e65504fa..c659041c5584 100644 --- a/Gax/src/ServerStream.php +++ b/Gax/src/ServerStream.php @@ -1,4 +1,6 @@ null, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $httpHandler = $config['httpHandler'] ?: self::buildHttpHandlerAsync(logger: $config['logger']); $transport = new GrpcFallbackTransport("$baseUri:$port", $httpHandler); if ($config['clientCertSource']) { diff --git a/Gax/src/Transport/GrpcTransport.php b/Gax/src/Transport/GrpcTransport.php index 5fd03a6fe52d..1881335467f7 100644 --- a/Gax/src/Transport/GrpcTransport.php +++ b/Gax/src/Transport/GrpcTransport.php @@ -1,4 +1,6 @@ null, 'logger' => null, ]; - list($addr, $port) = self::normalizeServiceAddress($apiEndpoint); + list($addr, $port) = self::normalizeApiEndpoint($apiEndpoint); $host = "$addr:$port"; $stubOpts = $config['stubOpts']; // Set the required 'credentials' key in stubOpts if it is not already set. Use diff --git a/Gax/src/Transport/HttpUnaryTransportTrait.php b/Gax/src/Transport/HttpUnaryTransportTrait.php index 38c4ca1f5522..8a9b3bea16b7 100644 --- a/Gax/src/Transport/HttpUnaryTransportTrait.php +++ b/Gax/src/Transport/HttpUnaryTransportTrait.php @@ -1,4 +1,6 @@ false, 'logger' => null, ]; - list($baseUri, $port) = self::normalizeServiceAddress($apiEndpoint); + list($baseUri, $port) = self::normalizeApiEndpoint($apiEndpoint); $requestBuilder = $config['hasEmulator'] ? new InsecureRequestBuilder("$baseUri:$port", $restConfigPath) : new RequestBuilder("$baseUri:$port", $restConfigPath); diff --git a/Gax/src/Transport/TransportInterface.php b/Gax/src/Transport/TransportInterface.php index 682a4301989c..8ae6d918c590 100644 --- a/Gax/src/Transport/TransportInterface.php +++ b/Gax/src/Transport/TransportInterface.php @@ -1,4 +1,6 @@ getAuthorizationHeaderCallback()(); } - /** - * Same test as above, but calls the deprecated CredentialsWrapper::getBearerString method - * instead of CredentialsWrapper::getAuthorizationHeaderCallback - * @dataProvider provideCheckUniverseDomainFails - */ - public function testCheckUniverseDomainOnGetBearerStringFails( - ?string $universeDomain, - ?string $credentialsUniverse, - ?string $message = null - ) { - $this->expectException(ValidationException::class); - $this->expectExceptionMessage($message ?: sprintf( - 'The configured universe domain (%s) does not match the credential universe domain (%s)', - is_null($universeDomain) ? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN : $universeDomain, - is_null($credentialsUniverse) ? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN : $credentialsUniverse, - )); - $fetcher = $this->prophesize(FetchAuthTokenInterface::class); - // When the $credentialsUniverse is null, the fetcher doesn't implement GetUniverseDomainInterface - if (!is_null($credentialsUniverse)) { - $fetcher->willImplement(GetUniverseDomainInterface::class); - $fetcher->getUniverseDomain()->willReturn($credentialsUniverse); - } - $fetcher->getLastReceivedToken()->willReturn(null); - // When $universeDomain is null, it means no $universeDomain argument was provided - if (is_null($universeDomain)) { - $credentialsWrapper = new CredentialsWrapper($fetcher->reveal()); - } else { - $credentialsWrapper = new CredentialsWrapper($fetcher->reveal(), null, $universeDomain); - } - // Check getBearerString (deprecated) - $credentialsWrapper->getBearerString(); - } - public function provideCheckUniverseDomainFails() { return [ @@ -314,11 +281,6 @@ public function testCheckUniverseDomainPasses(?string $universeDomain, ?string $ ['authorization' => ['Bearer abc']], $credentialsWrapper->getAuthorizationHeaderCallback()() ); - // Check getBearerString (deprecated) - $this->assertEquals( - 'Bearer abc', - $credentialsWrapper->getBearerString() - ); } public function provideCheckUniverseDomainPasses() @@ -344,29 +306,6 @@ public function testCheckUniverseDomainOnGceCredentialsDoesNotCheck() $credentialsWrapper->checkUniverseDomain(); } - /** - * @dataProvider getBearerStringData - * @runInSeparateProcess - */ - public function testGetBearerString(string $fetcherFunc, $expectedBearerString) - { - $fetcher = $this->$fetcherFunc(); - $credentialsWrapper = new CredentialsWrapper($fetcher); - $bearerString = $credentialsWrapper->getBearerString(); - $this->assertSame($expectedBearerString, $bearerString); - } - - public function getBearerStringData() - { - return [ - ['getExpiredFetcher', 'Bearer 456'], - ['getEagerExpiredFetcher', 'Bearer 456'], - ['getUnexpiredFetcher', 'Bearer 123'], - ['getInsecureFetcher', ''], - ['getNullFetcher', ''], - ]; - } - /** * @dataProvider getAuthorizationHeaderCallbackData * @runInSeparateProcess diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index fef2951d4197..06c7b3fb58a1 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1581,17 +1581,17 @@ public function __invoke(Call $call, array $options) $transport->startUnaryCall( Argument::type(Call::class), [ - 'transportOptions' => [ - 'custom' => ['addModifyUnaryCallableOption' => true] - ], - 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'transportOptions' => [ + 'custom' => ['addModifyUnaryCallableOption' => true] + ], + 'headers' => AgentHeader::buildAgentHeader([]), + 'credentialsWrapper' => CredentialsWrapper::build([ + 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' + ]) ] ) - ->shouldBeCalledOnce() - ->willReturn(new FulfilledPromise(new Operation())); + ->shouldBeCalledOnce() + ->willReturn(new FulfilledPromise(new Operation())); $client->startCall( 'simpleMethod', diff --git a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php index 7d7dac94189e..1c264ae76ee9 100644 --- a/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/OperationsMiddlewareTest.php @@ -33,9 +33,9 @@ namespace Google\ApiCore\Tests\Unit\Middleware; use Google\ApiCore\Call; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\ApiCore\Middleware\OperationsMiddleware; -use Google\ApiCore\Testing\MockResponse; +use Google\ApiCore\Testing\MockRequest; use GuzzleHttp\Promise\Promise; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; @@ -50,11 +50,11 @@ public function testOperationNameMethodDescriptor() $operationsClient = $this->prophesize(OperationsClient::class); $descriptor = [ - 'operationNameMethod' => 'getNumber' + 'operationNameMethod' => 'getPageToken' ]; $handler = function (Call $call, $options) use (&$callCount) { return $promise = new Promise(function () use (&$promise) { - $response = new MockResponse(['number' => 123]); + $response = new MockRequest(['page_token' => 'abc']); $promise->resolve($response); }); }; @@ -64,6 +64,6 @@ public function testOperationNameMethodDescriptor() [] )->wait(); - $this->assertEquals(123, $response->getName()); + $this->assertEquals('abc', $response->getName()); } } diff --git a/Gax/tests/Unit/ServiceAddressTraitTest.php b/Gax/tests/Unit/ServiceAddressTraitTest.php deleted file mode 100644 index ba5cf81c7a64..000000000000 --- a/Gax/tests/Unit/ServiceAddressTraitTest.php +++ /dev/null @@ -1,69 +0,0 @@ -assertSame($expectedAddress, $actualAddress); - $this->assertSame($expectedPort, $actualPort); - } - - public function normalizeServiceAddressData() - { - return [ - ['simple.com:123', 'simple.com', '123'], - ['really.long.and.dotted:456', 'really.long.and.dotted', '456'], - ['noport.com', 'noport.com', self::$defaultPort], - ]; - } - - /** - * @dataProvider normalizeServiceAddressInvalidData - */ - public function testNormalizeServiceAddressInvalid($serviceAddressString) - { - $this->expectException(ValidationException::class); - $this->expectExceptionMessage('Invalid apiEndpoint'); - - self::normalizeServiceAddress($serviceAddressString); - } - - public function normalizeServiceAddressInvalidData() - { - return [ - ['too.many:colons:123'], - ['too:many:colons'], - ]; - } -} diff --git a/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php b/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php index d5a022de7c78..4520de072c76 100644 --- a/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php +++ b/Gax/tests/Unit/testdata/mocks/src/GapicClientStub.php @@ -1,4 +1,6 @@ Date: Tue, 16 Jun 2026 12:49:40 -0700 Subject: [PATCH 04/15] add new ApiEndpoint trait --- Gax/src/ApiEndpointTrait.php | 62 +++++++++++++++++++++++ Gax/tests/Unit/ApiEndpointTraitTest.php | 65 +++++++++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 Gax/src/ApiEndpointTrait.php create mode 100644 Gax/tests/Unit/ApiEndpointTraitTest.php diff --git a/Gax/src/ApiEndpointTrait.php b/Gax/src/ApiEndpointTrait.php new file mode 100644 index 000000000000..df74fed5ccba --- /dev/null +++ b/Gax/src/ApiEndpointTrait.php @@ -0,0 +1,62 @@ +assertSame($expectedAddress, $actualAddress); + $this->assertSame($expectedPort, $actualPort); + } + + public function normalizeApiEndpointData() + { + return [ + ['simple.com:123', 'simple.com', '123'], + ['really.long.and.dotted:456', 'really.long.and.dotted', '456'], + ['noport.com', 'noport.com', self::$defaultPort], + ]; + } + + /** + * @dataProvider normalizeApiEndpointInvalidData + */ + public function testNormalizeApiEndpointInvalid($ApiEndpointString) + { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('Invalid apiEndpoint'); + + self::normalizeApiEndpoint($ApiEndpointString); + } + + public function normalizeApiEndpointInvalidData() + { + return [ + ['too.many:colons:123'], + ['too:many:colons'], + ]; + } +} From dc3368c6981c0889506c3e0fe8009e4415eadafb Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Tue, 23 Jun 2026 11:26:30 -0700 Subject: [PATCH 05/15] drop v1-surface operations client, backwards compatibility mode --- Gax/src/ClientOptionsTrait.php | 39 ----------- Gax/src/GapicClientTrait.php | 64 +++++-------------- Gax/src/OperationResponse.php | 36 +++-------- Gax/tests/Unit/ApiEndpointTraitTest.php | 8 +-- Gax/tests/Unit/OperationResponseTest.php | 26 ++++---- .../CustomOperation/CustomOperationClient.php | 6 +- Ids/src/V1/Client/IDSClient.php | 19 ------ 7 files changed, 45 insertions(+), 153 deletions(-) diff --git a/Gax/src/ClientOptionsTrait.php b/Gax/src/ClientOptionsTrait.php index 7c00c0c58ad6..b231f506b78c 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -187,25 +187,6 @@ private function buildClientOptions(array|ClientOptions $options) $options['transportConfig']['grpc-fallback']['logger'] = $options['logger'] ?? null; } - // These calls do not apply to "New Surface" clients. - if ($this->isBackwardsCompatibilityMode()) { - $preModifiedOptions = $options; - $this->modifyClientOptions($options); - // NOTE: this is required to ensure backwards compatiblity with $options['apiEndpoint'] - if ($options['apiEndpoint'] !== $preModifiedOptions['apiEndpoint']) { - $apiEndpoint = $options['apiEndpoint']; - } - - // serviceAddress is now deprecated and acts as an alias for apiEndpoint - if (isset($options['serviceAddress'])) { - $apiEndpoint = $this->pluck('serviceAddress', $options, false); - } - } else { - // Ads is using this method in their new surface clients, so we need to call it. - // However, this method is not used anywhere else for the new surface clients - // @TODO: Remove this in GAX V2 - $this->modifyClientOptions($options); - } // If an API endpoint is different form the default, ensure the "audience" does not conflict // with the custom endpoint by setting "user defined" scopes. if ($apiEndpoint @@ -356,26 +337,6 @@ private static function supportedTransports() // functionality. These extension points are currently considered // private and may change at any time. - /** - * Modify options passed to the client before calling setClientOptions. - * - * @param array $options - * @access private - * @internal - */ - protected function modifyClientOptions(array &$options) - { - // Do nothing - this method exists to allow option modification by partial veneers. - } - - /** - * @internal - */ - private function isBackwardsCompatibilityMode(): bool - { - return false; - } - /** * @param null|false|LoggerInterface $logger * @param string $options diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index d3b9131dda3b..1e3f4a198ce2 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -50,8 +50,8 @@ use Google\ApiCore\Transport\RestTransport; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; -use Google\LongRunning\OperationsClient; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; @@ -285,20 +285,8 @@ private function setClientOptions(array $options) // Therefore, we need to remove it from the $options array before // creating the ClientOptions. $hasEmulator = $this->pluck('hasEmulator', $options, false) ?? false; - if ($this->isBackwardsCompatibilityMode()) { - if (is_string($options['clientConfig'])) { - // perform validation for V1 surfaces which is done in the - // ClientOptions class for v2 surfaces. - $options['clientConfig'] = json_decode( - file_get_contents($options['clientConfig']), - true - ); - self::validateFileExists($options['descriptorsConfigPath']); - } - } else { - // cast to ClientOptions for new surfaces only - $options = new ClientOptions($options); - } + // cast to ClientOptions for new surfaces only + $options = new ClientOptions($options); $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( $this->serviceName, @@ -321,14 +309,6 @@ private function setClientOptions(array $options) } $this->agentHeader = AgentHeader::buildAgentHeader($headerInfo); - // Set "client_library_name" depending on client library surface being used - $userAgentHeader = sprintf( - 'gcloud-php-%s/%s', - $this->isBackwardsCompatibilityMode() ? 'legacy' : 'new', - $options['gapicVersion'] - ); - $this->agentHeader['User-Agent'] = [$userAgentHeader]; - self::validateFileExists($options['descriptorsConfigPath']); $descriptors = require($options['descriptorsConfigPath']); @@ -434,26 +414,26 @@ private function createTransport( } /** - * @param array $options + * Create the default operation client for the service. + * + * @param array $options ClientOptions for the client. + * * @return OperationsClient */ private function createOperationsClient(array $options) { - $this->pluckArray([ - 'serviceName', - 'clientConfig', - 'descriptorsConfigPath', - ], $options); + // Unset client-specific configuration options + unset( + $options['serviceName'], + $options['clientConfig'], + $options['descriptorsConfigPath'] + ); - // User-supplied operations client - if ($operationsClient = $this->pluck('operationsClient', $options, false)) { - return $operationsClient; + if (isset($options['operationsClient'])) { + return $options['operationsClient']; } - // operationsClientClass option - $operationsClientClass = $this->pluck('operationsClientClass', $options, false) - ?: OperationsCLient::class; - return new $operationsClientClass($options); + return new OperationsClient($options); } /** @@ -768,9 +748,6 @@ private function configureCallConstructionOptions(string $methodName, array $opt */ private function configureCallOptions(array $optionalArgs): array { - if ($this->isBackwardsCompatibilityMode()) { - return $optionalArgs; - } // cast to CallOptions for new surfaces only return (new CallOptions($optionalArgs))->toArray(); } @@ -1009,13 +986,4 @@ protected function modifyStreamingCallable(callable &$callable) { // Do nothing - this method exists to allow callable modification by partial veneers. } - - /** - * @internal - */ - private function isBackwardsCompatibilityMode(): bool - { - return $this->backwardsCompatibilityMode - ?? $this->backwardsCompatibilityMode = substr(__CLASS__, -11) === 'GapicClient'; - } } diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 1f2bcb5903aa..e0d745c44400 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -39,7 +39,6 @@ use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; -use Google\LongRunning\OperationsClient as LegacyOperationsClient; use Google\Protobuf\Any; use Google\Protobuf\Internal\Message; use Google\Rpc\Status; @@ -279,8 +278,10 @@ public function reload() throw new ValidationException('Cannot call reload() on a deleted operation'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->getOperationRequest : null; - $this->lastProtoResponse = $this->operationsCall($this->getOperationMethod, $requestClass); + $this->lastProtoResponse = $this->operationsCall( + $this->getOperationMethod, + $this->getOperationRequest + ); } /** @@ -405,8 +406,7 @@ public function cancel() throw new LogicException('The cancel operation is not supported by this API'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->cancelOperationRequest : null; - $this->operationsCall($this->cancelOperationMethod, $requestClass); + $this->operationsCall($this->cancelOperationMethod, $this->cancelOperationRequest); } /** @@ -426,8 +426,7 @@ public function delete() throw new LogicException('The delete operation is not supported by this API'); } - $requestClass = $this->isNewSurfaceOperationsClient() ? $this->deleteOperationRequest : null; - $this->operationsCall($this->deleteOperationMethod, $requestClass); + $this->operationsCall($this->deleteOperationMethod, $this->deleteOperationRequest); $this->deleted = true; } @@ -473,26 +472,15 @@ public function getMetadata() * Call the operations client to perform an operation. * * @param string $method The method to call on the operations client. - * @param string|null $requestClass The request class to use for the call. + * @param string $requestClass The request class to use for the call. * Will be null for legacy operations clients. */ - private function operationsCall(string $method, ?string $requestClass) + private function operationsCall(string $method, string $requestClass) { - // V1 GAPIC clients have an empty $requestClass - if (empty($requestClass)) { - if ($this->additionalArgs) { - return $this->operationsClient->$method( - $this->getName(), - ...array_values($this->additionalArgs) - ); - } - return $this->operationsClient->$method($this->getName()); - } - if (!method_exists($requestClass, 'build')) { throw new LogicException('Request class must support the static build method'); } - // In V2 of Compute, the Request "build" methods contain the operation ID last instead + // In Compute, the Request "build" methods contain the operation ID last instead // of first. Compute is the only API which uses $additionalArgs, so switching the order // will not break anything. $request = $requestClass::build(...array_merge( @@ -532,10 +520,4 @@ private function hasProtoResponse() { return !is_null($this->lastProtoResponse); } - - private function isNewSurfaceOperationsClient(): bool - { - return !$this->operationsClient instanceof LegacyOperationsClient - && false !== strpos(get_class($this->operationsClient), self::NEW_CLIENT_NAMESPACE); - } } diff --git a/Gax/tests/Unit/ApiEndpointTraitTest.php b/Gax/tests/Unit/ApiEndpointTraitTest.php index 046909d61b44..807f2beee0d7 100644 --- a/Gax/tests/Unit/ApiEndpointTraitTest.php +++ b/Gax/tests/Unit/ApiEndpointTraitTest.php @@ -28,9 +28,9 @@ class ApiEndpointTraitTest extends TestCase /** * @dataProvider normalizeApiEndpointData */ - public function testNormalizeApiEndpoint($ApiEndpointString, $expectedAddress, $expectedPort) + public function testNormalizeApiEndpoint($apiEndpointString, $expectedAddress, $expectedPort) { - list($actualAddress, $actualPort) = self::normalizeApiEndpoint($ApiEndpointString); + list($actualAddress, $actualPort) = self::normalizeApiEndpoint($apiEndpointString); $this->assertSame($expectedAddress, $actualAddress); $this->assertSame($expectedPort, $actualPort); } @@ -47,12 +47,12 @@ public function normalizeApiEndpointData() /** * @dataProvider normalizeApiEndpointInvalidData */ - public function testNormalizeApiEndpointInvalid($ApiEndpointString) + public function testNormalizeApiEndpointInvalid($apiEndpointString) { $this->expectException(ValidationException::class); $this->expectExceptionMessage('Invalid apiEndpoint'); - self::normalizeApiEndpoint($ApiEndpointString); + self::normalizeApiEndpoint($apiEndpointString); } public function normalizeApiEndpointInvalidData() diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 0901be1bb5c8..4ef50bb3ac77 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -38,14 +38,14 @@ use Google\CustomOperation\CustomOperationWithErrorAnnotations; use Google\CustomOperation\DeleteOperationRequest as CustomDeleteOperationRequest; use Google\CustomOperation\GetOperationRequest as CustomGetOperationRequest; -use Google\ApiCore\LongRunning\OperationsClient; use Google\ApiCore\OperationResponse; use Google\LongRunning\CancelOperationRequest; -use Google\LongRunning\Client\OperationsClient as LROOperationsClient; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\DeleteOperationRequest; use Google\LongRunning\GetOperationRequest; use Google\LongRunning\Operation; use Google\Protobuf\Any; +use Google\Protobuf\Internal\Message; use Google\Rpc\Code; use LogicException; use PHPUnit\Framework\TestCase; @@ -78,7 +78,7 @@ public function provideOperationsClients() { return [ [$this->createOperationsClient()], - [$this->prophesize(LROOperationsClient::class)->reveal()], + [$this->prophesize(OperationsClient::class)->reveal()], ]; } @@ -237,13 +237,13 @@ public function testCustomOperation() ->shouldBeCalledOnce() ->willReturn(null); $operationClient = $this->prophesize(CustomOperationClient::class); - $operationClient->getMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->getMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn($operation->reveal()); - $operationClient->cancelMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->cancelMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn(true); - $operationClient->deleteMyOperationPlease($operationName, 'arg1', 'arg2') + $operationClient->deleteMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn(true); $options = [ @@ -481,9 +481,9 @@ public function testPollingCastToInt() $this->assertEquals($op->getSleeps(), [3, 4, 6]); } - public function testReloadWithLROOperationsClient() + public function testReloadWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new GetOperationRequest(['name' => 'test-123']); $operationClient->getOperation($request) ->shouldBeCalledOnce() @@ -493,9 +493,9 @@ public function testReloadWithLROOperationsClient() $operationResponse->reload(); } - public function testCancelWithLROOperationsClient() + public function testCancelWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new CancelOperationRequest(['name' => 'test-123']); $operationClient->cancelOperation($request) ->shouldBeCalledOnce(); @@ -504,9 +504,9 @@ public function testCancelWithLROOperationsClient() $operationResponse->cancel(); } - public function testDeleteWithLROOperationsClient() + public function testDeleteWithOperationsClient() { - $operationClient = $this->prophesize(LROOperationsClient::class); + $operationClient = $this->prophesize(OperationsClient::class); $request = new DeleteOperationRequest(['name' => 'test-123']); $operationClient->deleteOperation($request) ->shouldBeCalledOnce(); @@ -555,7 +555,7 @@ private function createOperationClient($reloadCount) $opClient = $this->prophesize(OperationsClient::class); - $opClient->getOperation(Argument::type('string')) + $opClient->getOperation(Argument::type('object')) ->shouldBeCalledTimes($reloadCount) ->willReturn(...$consecutiveCalls); diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php index f7d992940db5..1b1b5def6ad2 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationClient.php @@ -4,7 +4,7 @@ interface CustomOperationClient { - public function getMyOperationPlease($name, $requiredArg1, $requiredArg2); - public function cancelMyOperationPlease($name, $requiredArg1, $requiredArg2); - public function deleteMyOperationPlease($name, $requiredArg1, $requiredArg2); + public function getMyOperationPlease($request); + public function cancelMyOperationPlease($request); + public function deleteMyOperationPlease($request); } diff --git a/Ids/src/V1/Client/IDSClient.php b/Ids/src/V1/Client/IDSClient.php index 1cc149b391ad..653622e81c40 100644 --- a/Ids/src/V1/Client/IDSClient.php +++ b/Ids/src/V1/Client/IDSClient.php @@ -138,25 +138,6 @@ public function resumeOperation($operationName, $methodName = null) return $operation; } - /** - * Create the default operation client for the service. - * - * @param array $options ClientOptions for the client. - * - * @return OperationsClient - */ - private function createOperationsClient(array $options) - { - // Unset client-specific configuration options - unset($options['serviceName'], $options['clientConfig'], $options['descriptorsConfigPath']); - - if (isset($options['operationsClient'])) { - return $options['operationsClient']; - } - - return new OperationsClient($options); - } - /** * Formats a string containing the fully-qualified path to represent a endpoint * resource. From ed0e050d7818d25c264cafa916d8d19300e20bbd Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 6 Jul 2026 11:27:37 -0700 Subject: [PATCH 06/15] Remove legacy headers --- Gax/tests/Unit/GapicClientTraitTest.php | 41 +------------------------ 1 file changed, 1 insertion(+), 40 deletions(-) diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 06c7b3fb58a1..635550fabcd9 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -887,7 +887,7 @@ public function setClientOptionsData() } $expectedProperties = [ 'serviceName' => 'test.interface.v1.api', - 'agentHeader' => AgentHeader::buildAgentHeader([]) + ['User-Agent' => ['gcloud-php-legacy/']], + 'agentHeader' => AgentHeader::buildAgentHeader([]), 'retrySettings' => $expectedRetrySettings, ]; return [ @@ -979,18 +979,6 @@ public function buildRequestHeaderParams() ]; } - public function testModifyClientOptions() - { - $options = []; - $client = new StubGapicClientExtension(); - $updatedOptions = $client->buildClientOptions($options); - $client->setClientOptions($updatedOptions); - - $this->assertArrayHasKey('addNewOption', $updatedOptions); - $this->assertTrue($updatedOptions['disableRetries']); - $this->assertEquals('abc123', $updatedOptions['apiEndpoint']); - } - private function buildClientToTestModifyCallMethods($clientClass = null) { $header = AgentHeader::buildAgentHeader([]); @@ -1206,7 +1194,6 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() [ 'headers' => AgentHeader::buildAgentHeader([]) + [ 'X-Goog-User-Project' => [$quotaProject], - 'User-Agent' => ['gcloud-php-legacy/'] ], 'credentialsWrapper' => $credentialsWrapper->reveal() ] @@ -1701,25 +1688,6 @@ public function testInvalidCallOptionsTypeForV2SurfaceThrowsException() )->wait(); } - public function testSurfaceAgentHeaders() - { - // V1 does not contain new headers - $client = new RestOnlyGapicClient([ - 'gapicVersion' => '0.0.2', - ]); - $agentHeader = $client->getAgentHeader(); - $this->assertStringContainsString(' gapic/0.0.2 ', $agentHeader['x-goog-api-client'][0]); - $this->assertEquals('gcloud-php-legacy/0.0.2', $agentHeader['User-Agent'][0]); - - // V2 contains new headers - $client = new GapicV2SurfaceClient([ - 'gapicVersion' => '0.0.1', - ]); - $agentHeader = $client->getAgentHeader(); - $this->assertStringContainsString(' gapic/0.0.1 ', $agentHeader['x-goog-api-client'][0]); - $this->assertEquals('gcloud-php-new/0.0.1', $agentHeader['User-Agent'][0]); - } - public function testApiKeyOption() { $transport = $this->prophesize(TransportInterface::class); @@ -1919,13 +1887,6 @@ public function get($name) class StubGapicClientExtension extends StubGapicClient { - protected function modifyClientOptions(array &$options) - { - $options['disableRetries'] = true; - $options['addNewOption'] = true; - $options['apiEndpoint'] = 'abc123'; - } - protected function modifyUnaryCallable(callable &$callable) { $originalCallable = $callable; From 88b24fdbf222bd5096e9a502788f4e38fb0cf02d Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 28 Sep 2026 19:17:55 +0000 Subject: [PATCH 07/15] chore!(gax): remove remaining v1 deprecations, add client interfaces, and tighten typehints --- Datastore/tests/Unit/DatastoreClientTest.php | 3 +- Firestore/tests/Unit/BulkWriterTest.php | 4 +- Firestore/tests/Unit/ConformanceTest.php | 4 +- Firestore/tests/Unit/FirestoreClientTest.php | 4 +- Gax/composer.json | 1 - Gax/src/AgentHeader.php | 4 +- Gax/src/ArrayTrait.php | 12 +- Gax/src/BidiStream.php | 26 +- Gax/src/Call.php | 32 +- Gax/src/ClientOptionsTrait.php | 92 ++---- Gax/src/ClientStream.php | 12 +- Gax/src/CredentialsWrapper.php | 66 ++-- Gax/src/FixedSizeCollection.php | 24 +- Gax/src/GapicClientTrait.php | 79 ++--- Gax/src/HeaderCredentialsInterface.php | 4 +- Gax/src/IamProviderInterface.php | 53 ++++ Gax/src/InsecureCredentialsWrapper.php | 16 +- .../LongRunningOperationProviderInterface.php | 44 +++ Gax/src/Middleware/RetryMiddleware.php | 2 +- Gax/src/OperationResponse.php | 58 ++-- Gax/src/Options/CallOptions.php | 17 +- Gax/src/Options/ClientOptions.php | 41 +-- Gax/src/Page.php | 44 +-- Gax/src/PagedListResponse.php | 19 +- Gax/src/PollingTrait.php | 6 +- Gax/src/ResourceHelperTrait.php | 12 +- .../RelativeResourceTemplate.php | 2 +- Gax/src/ResumableUpload/ResumableUpload.php | 2 + .../ResumableUpload/ResumableUploadClient.php | 8 +- .../ResumableUpload/ResumableUploadState.php | 2 + .../ResumableUpload/ResumableUploadTrait.php | 2 + .../ResumableUploadTransportInterface.php | 2 + Gax/src/RetrySettings.php | 60 ++-- Gax/src/ServerStream.php | 12 +- Gax/src/ServiceInterface.php | 46 +++ .../Grpc/ServerStreamingCallWrapper.php | 11 +- .../Rest/RestServerStreamingCall.php | 2 +- Gax/src/UriTrait.php | 2 +- Gax/src/ValidationTrait.php | 8 +- Gax/src/Version.php | 9 +- .../Testing/MockGrpcTransport.php | 2 +- Gax/tests/Unit/ClientOptionsTraitTest.php | 73 +---- Gax/tests/Unit/CredentialsWrapperTest.php | 82 +---- Gax/tests/Unit/GapicClientTraitTest.php | 288 +++++++++--------- Gax/tests/Unit/OperationResponseTest.php | 6 +- .../Unit/Transport/GrpcTransportTest.php | 12 +- .../CustomOperation/GetOperationRequest.php | 4 +- .../mocks/DeprecatedTestInterceptor.php | 32 -- .../mocks/DeprecatedTestUnaryInterceptor.php | 20 -- .../resources/test_service_grpc_config.json | 17 -- PubSub/tests/Unit/BatchPublisherTest.php | 6 +- PubSub/tests/Unit/PubSubClientTest.php | 4 +- .../src/OpenTelemetry/OtlpMetricsExporter.php | 6 +- Spanner/src/SpannerClient.php | 7 +- Spanner/tests/Unit/DatabaseTest.php | 4 +- .../Unit/RequestIdHeaderMiddlewareTest.php | 4 +- Spanner/tests/Unit/SpannerClientTest.php | 34 +-- composer.json | 1 - phpcs-ruleset.xml | 1 + 59 files changed, 627 insertions(+), 823 deletions(-) create mode 100644 Gax/src/IamProviderInterface.php create mode 100644 Gax/src/LongRunningOperationProviderInterface.php create mode 100644 Gax/src/ServiceInterface.php rename Gax/{src => tests}/Testing/MockGrpcTransport.php (99%) delete mode 100644 Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php delete mode 100644 Gax/tests/Unit/testdata/mocks/DeprecatedTestUnaryInterceptor.php delete mode 100644 Gax/tests/Unit/testdata/resources/test_service_grpc_config.json diff --git a/Datastore/tests/Unit/DatastoreClientTest.php b/Datastore/tests/Unit/DatastoreClientTest.php index f12be54432c8..bf3990865960 100644 --- a/Datastore/tests/Unit/DatastoreClientTest.php +++ b/Datastore/tests/Unit/DatastoreClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Datastore\Tests\Unit; use DateTime; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\Transport\TransportInterface; use Google\Cloud\Core\Int64; use Google\Cloud\Core\Testing\DatastoreOperationRefreshTrait; @@ -82,7 +83,7 @@ public function setUp(): void { $this->gapicClient = $this->prophesize(GapicClient::class); $this->client = new DatastoreClient([ - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'projectId' => self::PROJECT, 'databaseId' => self::DATABASE, 'datastoreClient' => $this->gapicClient->reveal() diff --git a/Firestore/tests/Unit/BulkWriterTest.php b/Firestore/tests/Unit/BulkWriterTest.php index 64a47ada90db..744cb4d91678 100644 --- a/Firestore/tests/Unit/BulkWriterTest.php +++ b/Firestore/tests/Unit/BulkWriterTest.php @@ -17,7 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; -use Google\Cloud\Core\Testing\Snippet\Fixtures; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\BulkWriter; @@ -72,7 +72,7 @@ public function setUp(): void 'projectId' => self::PROJECT, 'database' => self::DATABASE, 'firestoreClient' => $this->gapicClient->reveal(), - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]); // avoids sleep during unit tests diff --git a/Firestore/tests/Unit/ConformanceTest.php b/Firestore/tests/Unit/ConformanceTest.php index 2f91202debc9..862b04c8aeae 100644 --- a/Firestore/tests/Unit/ConformanceTest.php +++ b/Firestore/tests/Unit/ConformanceTest.php @@ -17,8 +17,8 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Core\Timestamp; use Google\Cloud\Core\TimeTrait; use Google\Cloud\Firestore\CollectionReference; @@ -94,7 +94,7 @@ public function setUp(): void $this->client = new FirestoreClient([ 'firestoreClient' => $this->gapicClient->reveal(), 'projectId' => self::PROJECT_ID, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]); } diff --git a/Firestore/tests/Unit/FirestoreClientTest.php b/Firestore/tests/Unit/FirestoreClientTest.php index 85fcfb0f6073..e28fb92284a2 100644 --- a/Firestore/tests/Unit/FirestoreClientTest.php +++ b/Firestore/tests/Unit/FirestoreClientTest.php @@ -38,10 +38,10 @@ use Google\Cloud\Firestore\V1\CommitRequest; use Google\Cloud\Firestore\V1\CommitResponse; use Google\Cloud\Firestore\V1\ListCollectionIdsRequest; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\ServerStream; use Google\Cloud\Core\Exception\BadRequestException; use Google\Cloud\Core\Exception\ServiceException; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Firestore\V1\BatchGetDocumentsRequest; use Google\Cloud\Firestore\V1\BatchGetDocumentsResponse; use Google\Cloud\Firestore\V1\BeginTransactionRequest; @@ -85,7 +85,7 @@ public function setUp(): void 'projectId' => self::PROJECT, 'database' => self::DATABASE, 'firestoreClient' => $this->gapicClient->reveal(), - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]); } diff --git a/Gax/composer.json b/Gax/composer.json index f904c2ffe5a3..a29a5a553b4d 100644 --- a/Gax/composer.json +++ b/Gax/composer.json @@ -10,7 +10,6 @@ "require": { "php": "^8.2", "google/auth": "^1.53", - "google/grpc-gcp": "^0.4", "grpc/grpc": "^1.38", "google/protobuf": "^4.31||^5.34", "guzzlehttp/promises": "^2.0.3||^3.0", diff --git a/Gax/src/AgentHeader.php b/Gax/src/AgentHeader.php index 4754a9752fff..7365748b2bed 100644 --- a/Gax/src/AgentHeader.php +++ b/Gax/src/AgentHeader.php @@ -61,7 +61,7 @@ class AgentHeader * } * @return array Agent header array */ - public static function buildAgentHeader(array $headerInfo) + public static function buildAgentHeader(array $headerInfo): array { $metricsHeaders = []; @@ -120,7 +120,7 @@ public static function buildAgentHeader(array $headerInfo) * @return string the gapic version * @throws \ReflectionException */ - public static function readGapicVersionFromFile(string $callingClass) + public static function readGapicVersionFromFile(string $callingClass): string { $callingClassFile = (new \ReflectionClass($callingClass))->getFileName(); $versionFile = substr( diff --git a/Gax/src/ArrayTrait.php b/Gax/src/ArrayTrait.php index 2e57e10ea770..ceba1482c803 100644 --- a/Gax/src/ArrayTrait.php +++ b/Gax/src/ArrayTrait.php @@ -50,7 +50,7 @@ trait ArrayTrait * @return mixed|null * @throws \InvalidArgumentException */ - private function pluck(string $key, array &$arr, bool $isRequired = true) + private function pluck(string $key, array &$arr, bool $isRequired = true): mixed { if (!array_key_exists($key, $arr)) { if ($isRequired) { @@ -74,7 +74,7 @@ private function pluck(string $key, array &$arr, bool $isRequired = true) * @param array $arr * @return array */ - private function pluckArray(array $keys, array &$arr) + private function pluckArray(array $keys, array &$arr): array { $values = []; @@ -93,7 +93,7 @@ private function pluckArray(array $keys, array &$arr) * @param array $arr * @return bool */ - private function isAssoc(array $arr) + private function isAssoc(array $arr): bool { return array_keys($arr) !== range(0, count($arr) - 1); } @@ -104,7 +104,7 @@ private function isAssoc(array $arr) * @param array $arr * @return array */ - private function arrayFilterRemoveNull(array $arr) + private function arrayFilterRemoveNull(array $arr): array { return array_filter($arr, function ($element) { if (!is_null($element)) { @@ -122,7 +122,7 @@ private function arrayFilterRemoveNull(array $arr) * @param array $arr * @return array */ - private function subsetArray(array $keys, array $arr) + private function subsetArray(array $keys, array $arr): array { return array_intersect_key( $arr, @@ -141,7 +141,7 @@ private function subsetArray(array $keys, array $arr) * @param array $array2 * @return array */ - private function arrayMergeRecursive(array $array1, array $array2) + private function arrayMergeRecursive(array $array1, array $array2): array { foreach ($array2 as $key => $value) { if (array_key_exists($key, $array1) && is_array($array1[$key]) && is_array($value)) { diff --git a/Gax/src/BidiStream.php b/Gax/src/BidiStream.php index 29304decd232..58608a89bb2c 100644 --- a/Gax/src/BidiStream.php +++ b/Gax/src/BidiStream.php @@ -47,11 +47,11 @@ class BidiStream { use LoggingTrait; - private $call; - private $isComplete = false; - private $writesClosed = false; - private $resourcesGetMethod = null; - private $pendingResources = []; + private BidiStreamingCall $call; + private bool $isComplete = false; + private bool $writesClosed = false; + private ?string $resourcesGetMethod = null; + private array $pendingResources = []; private null|LoggerInterface $logger = null; /** @@ -79,7 +79,7 @@ public function __construct( * @param mixed $request The request to write * @throws ValidationException */ - public function write($request) + public function write(mixed $request): void { if ($this->isComplete) { throw new ValidationException('Cannot call write() after streaming call is complete.'); @@ -109,7 +109,7 @@ public function write($request) * * @throws ValidationException */ - public function writeAll($requests = []) + public function writeAll(iterable $requests = []): void { foreach ($requests as $request) { $this->write($request); @@ -121,7 +121,7 @@ public function writeAll($requests = []) * called after closeWrite() is called. * @throws ValidationException */ - public function closeWrite() + public function closeWrite(): void { if ($this->isComplete) { throw new ValidationException( @@ -142,7 +142,7 @@ public function closeWrite() * @throws ApiException * @return mixed */ - public function read() + public function read(): mixed { if ($this->isComplete) { throw new ValidationException('Cannot call read() after streaming call is complete.'); @@ -195,9 +195,9 @@ public function read() * * @throws ValidationException * @throws ApiException - * @return \Generator|mixed[] + * @return \Generator */ - public function closeWriteAndReadAll() + public function closeWriteAndReadAll(): iterable { $this->closeWrite(); $response = $this->read(); @@ -210,9 +210,9 @@ public function closeWriteAndReadAll() /** * Return the underlying gRPC call object * - * @return \Grpc\BidiStreamingCall|mixed + * @return BidiStreamingCall */ - public function getBidiStreamingCall() + public function getBidiStreamingCall(): BidiStreamingCall { return $this->call; } diff --git a/Gax/src/Call.php b/Gax/src/Call.php index 2878e7e6cec4..ace8d4b36f37 100644 --- a/Gax/src/Call.php +++ b/Gax/src/Call.php @@ -49,15 +49,15 @@ class Call const PAGINATED_CALL = 5; const RESUMABLE_UPLOAD_CALL = 6; - private $method; - private $callType; - private $decodeType; - private $message; - private $descriptor; + private string $method; + private int $callType; + private ?string $decodeType; + private mixed $message; + private ?array $descriptor; /** * @param string $method - * @param string $decodeType + * @param string|null $decodeType * @param mixed|Message $message * @param array|null $descriptor * @param int $callType @@ -65,8 +65,8 @@ class Call public function __construct( string $method, ?string $decodeType = null, - $message = null, - $descriptor = [], + mixed $message = null, + ?array $descriptor = [], int $callType = Call::UNARY_CALL ) { $this->method = $method; @@ -79,7 +79,7 @@ public function __construct( /** * @return string */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -87,15 +87,15 @@ public function getMethod() /** * @return int */ - public function getCallType() + public function getCallType(): int { return $this->callType; } /** - * @return string + * @return string|null */ - public function getDecodeType() + public function getDecodeType(): ?string { return $this->decodeType; } @@ -103,7 +103,7 @@ public function getDecodeType() /** * @return mixed|Message */ - public function getMessage() + public function getMessage(): mixed { return $this->message; } @@ -111,16 +111,16 @@ public function getMessage() /** * @return array|null */ - public function getDescriptor() + public function getDescriptor(): ?array { return $this->descriptor; } /** * @param mixed|Message $message - * @return Call + * @return static */ - public function withMessage($message) + public function withMessage(mixed $message): static { // @phpstan-ignore-next-line return new static( diff --git a/Gax/src/ClientOptionsTrait.php b/Gax/src/ClientOptionsTrait.php index b231f506b78c..b4c5eb4921ee 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -40,8 +40,6 @@ use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetUniverseDomainInterface; use Google\Auth\HttpHandler\HttpHandlerFactory; -use Grpc\Gcp\ApiConfig; -use Grpc\Gcp\Config; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; @@ -54,9 +52,9 @@ trait ClientOptionsTrait { use ArrayTrait; - private static $gapicVersionFromFile; + private static ?string $gapicVersionFromFile = null; - private static function getGapicVersion(array $options) + private static function getGapicVersion(array $options): string { if (isset($options['libVersion'])) { return $options['libVersion']; @@ -67,14 +65,6 @@ private static function getGapicVersion(array $options) return self::$gapicVersionFromFile; } - private static function initGrpcGcpConfig(string $hostName, string $confPath) - { - $apiConfig = new ApiConfig(); - $apiConfig->mergeFromJsonString(file_get_contents($confPath)); - $config = new Config($hostName, $apiConfig); - return $config; - } - /** * Get default options. This function should be "overridden" by clients using late static * binding to provide default options to the client. @@ -89,19 +79,17 @@ private static function getClientDefaults() /** * Resolve client options based on the client's default - * ({@see ClientOptionsTrait::getClientDefault}) and the default for all + * ({@see ClientOptionsTrait::getClientDefaults}) and the default for all * Google APIs. * * 1. Set default client option values * 2. Set default logger (and log user-supplied configuration options) * 3. Set default transport configuration - * 4. Call "modifyClientOptions" (for backwards compatibility) - * 5. Use "defaultScopes" when custom endpoint is supplied - * 6. Load mTLS from the environment if configured - * 7. Resolve endpoint based on universe domain template when possible - * 8. Load sysvshm grpc config when possible + * 4. Use "defaultScopes" when custom endpoint is supplied + * 5. Load mTLS from the environment if configured + * 6. Resolve endpoint based on universe domain template when possible */ - private function buildClientOptions(array|ClientOptions $options) + private function buildClientOptions(array|ClientOptions $options): array { if ($options instanceof ClientOptions) { $options = $options->toArray(); @@ -231,37 +219,9 @@ private function buildClientOptions(array|ClientOptions $options) } if (is_null($apiEndpoint)) { - if (defined('self::SERVICE_ADDRESS_TEMPLATE')) { - // Derive the endpoint from the service address template and the universe domain - $apiEndpoint = str_replace( - 'UNIVERSE_DOMAIN', - $options['universeDomain'], - self::SERVICE_ADDRESS_TEMPLATE - ); - } else { - // For older clients, the service address template does not exist. Use the default - // endpoint instead. - $apiEndpoint = $defaultOptions['apiEndpoint']; - } - } - - if (extension_loaded('sysvshm') - && isset($options['gcpApiConfigPath']) - && file_exists($options['gcpApiConfigPath']) - && !empty($apiEndpoint) - ) { - $grpcGcpConfig = self::initGrpcGcpConfig( - $apiEndpoint, - $options['gcpApiConfigPath'] - ); - - if (!array_key_exists('stubOpts', $options['transportConfig']['grpc'])) { - $options['transportConfig']['grpc']['stubOpts'] = []; - } - - $options['transportConfig']['grpc']['stubOpts'] += [ - 'grpc_call_invoker' => $grpcGcpConfig->callInvoker() - ]; + $apiEndpoint = defined('self::SERVICE_ADDRESS_TEMPLATE') + ? str_replace('UNIVERSE_DOMAIN', $options['universeDomain'], self::SERVICE_ADDRESS_TEMPLATE) + : $defaultOptions['apiEndpoint']; } $options['apiEndpoint'] = $apiEndpoint; @@ -269,7 +229,7 @@ private function buildClientOptions(array|ClientOptions $options) return $options; } - private function shouldUseMtlsEndpoint(array $options) + private function shouldUseMtlsEndpoint(array $options): bool { $mtlsEndpointEnvVar = getenv('GOOGLE_API_USE_MTLS_ENDPOINT'); if ('always' === $mtlsEndpointEnvVar) { @@ -282,7 +242,7 @@ private function shouldUseMtlsEndpoint(array $options) return !empty($options['clientCertSource']); } - private static function determineMtlsEndpoint(string $apiEndpoint) + private static function determineMtlsEndpoint(string $apiEndpoint): string { $parts = explode('.', $apiEndpoint); if (count($parts) < 3) { @@ -292,42 +252,34 @@ private static function determineMtlsEndpoint(string $apiEndpoint) } /** - * @param mixed $credentials + * @param FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * @param array $credentialsConfig - * @return CredentialsWrapper + * @param string $universeDomain + * @return HeaderCredentialsInterface * @throws ValidationException */ - private function createCredentialsWrapper($credentials, array $credentialsConfig, string $universeDomain) - { + private function createCredentialsWrapper( + FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + array $credentialsConfig, + string $universeDomain + ): HeaderCredentialsInterface { if (is_null($credentials)) { - // If the user has explicitly set the apiKey option, use Api Key credentials return CredentialsWrapper::build($credentialsConfig, $universeDomain); } - if (is_string($credentials) || is_array($credentials)) { - return CredentialsWrapper::build(['keyFile' => $credentials] + $credentialsConfig, $universeDomain); - } - if ($credentials instanceof FetchAuthTokenInterface) { $authHttpHandler = $credentialsConfig['authHttpHandler'] ?? null; return new CredentialsWrapper($credentials, $authHttpHandler, $universeDomain); } - if ($credentials instanceof CredentialsWrapper) { - return $credentials; - } - - throw new ValidationException(sprintf( - 'Unexpected value in $auth option, got: %s', - print_r($credentials, true) - )); + return $credentials; } /** * This defaults to all three transports, which One-Platform supports. * Discovery clients should define this function and only return ['rest']. */ - private static function supportedTransports() + private static function supportedTransports(): array { return ['grpc', 'grpc-fallback', 'rest']; } diff --git a/Gax/src/ClientStream.php b/Gax/src/ClientStream.php index a7622e5c8740..28abd96f8063 100644 --- a/Gax/src/ClientStream.php +++ b/Gax/src/ClientStream.php @@ -47,7 +47,7 @@ class ClientStream { use LoggingTrait; - private $call; + private ClientStreamingCall $call; private null|LoggerInterface $logger; /** @@ -71,7 +71,7 @@ public function __construct(// @phpstan-ignore-line * * @param mixed $request The request to write */ - public function write($request) + public function write(mixed $request): void { // In some cases, $request can be a string if ($this->logger && $request instanceof Message) { @@ -93,7 +93,7 @@ public function write($request) * @throws ApiException * @return mixed The response object from the server */ - public function readResponse() + public function readResponse(): mixed { list($response, $status) = $this->call->wait(); if ($status->code == Code::OK) { @@ -125,7 +125,7 @@ public function readResponse() * @param mixed[] $requests An iterator of request objects to write to the server * @return mixed The response object from the server */ - public function writeAllAndReadResponse(array $requests) + public function writeAllAndReadResponse(array $requests): mixed { foreach ($requests as $request) { $this->write($request); @@ -136,9 +136,9 @@ public function writeAllAndReadResponse(array $requests) /** * Return the underlying gRPC call object * - * @return \Grpc\ClientStreamingCall|mixed + * @return ClientStreamingCall */ - public function getClientStreamingCall() + public function getClientStreamingCall(): ClientStreamingCall { return $this->call; } diff --git a/Gax/src/CredentialsWrapper.php b/Gax/src/CredentialsWrapper.php index a5ebf016376d..f4a393e942ff 100644 --- a/Gax/src/CredentialsWrapper.php +++ b/Gax/src/CredentialsWrapper.php @@ -39,7 +39,6 @@ use Google\Auth\Cache\MemoryCacheItemPool; use Google\Auth\Credentials\GCECredentials; use Google\Auth\Credentials\ServiceAccountCredentials; -use Google\Auth\CredentialsLoader; use Google\Auth\FetchAuthTokenCache; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetQuotaProjectInterface; @@ -92,10 +91,6 @@ public function __construct( * @param array $args { * An array of optional arguments. * - * @type string|array $keyFile - * Credentials to be used. Accepts either a path to a credentials file, or a decoded - * credentials file as a PHP array. If this is not specified, application default - * credentials will be used. * @type string[] $scopes * A string array of scopes to use when acquiring credentials. * @type callable $authHttpHandler @@ -128,9 +123,8 @@ public function __construct( public static function build( array $args = [], string $universeDomain = GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN - ) { + ): self { $args += [ - 'keyFile' => null, 'scopes' => null, 'authHttpHandler' => null, 'enableCaching' => true, @@ -142,39 +136,17 @@ public static function build( 'enableRegionalAccessBoundary' => false, ]; - $keyFile = $args['keyFile']; - - if (is_null($keyFile)) { - $loader = self::buildApplicationDefaultCredentials( - $args['scopes'], - $args['authHttpHandler'], - $args['authCacheOptions'], - $args['authCache'], - $args['quotaProject'], - $args['defaultScopes'], - $args['enableRegionalAccessBoundary'], - ); - if ($loader instanceof FetchAuthTokenCache) { - $loader = $loader->getFetcher(); - } - } else { - if (is_string($keyFile)) { - if (!file_exists($keyFile)) { - throw new ValidationException("Could not find keyfile: $keyFile"); - } - $keyFile = json_decode(file_get_contents($keyFile), true); - } - - if (isset($args['quotaProject'])) { - $keyFile['quota_project_id'] = $args['quotaProject']; - } - - $loader = CredentialsLoader::makeCredentials( - $args['scopes'], - $keyFile, - $args['defaultScopes'], - $args['enableRegionalAccessBoundary'], - ); + $loader = self::buildApplicationDefaultCredentials( + $args['scopes'], + $args['authHttpHandler'], + $args['authCacheOptions'], + $args['authCache'], + $args['quotaProject'], + $args['defaultScopes'], + $args['enableRegionalAccessBoundary'], + ); + if ($loader instanceof FetchAuthTokenCache) { + $loader = $loader->getFetcher(); } if ($loader instanceof ServiceAccountCredentials && $args['useJwtAccessWithScope']) { @@ -221,10 +193,10 @@ public function getProjectId(?callable $httpHandler = null): ?string } /** - * @param string $audience optional audience for self-signed JWTs. - * @return callable Callable function that returns an authorization header. + * @param string|null $audience optional audience for self-signed JWTs. + * @return callable|null Callable function that returns an authorization header. */ - public function getAuthorizationHeaderCallback($audience = null): ?callable + public function getAuthorizationHeaderCallback(?string $audience = null): ?callable { // NOTE: changes to this function should be treated carefully and tested thoroughly. It will // be passed into the gRPC c extension, and changes have the potential to trigger very @@ -309,10 +281,10 @@ private static function buildApplicationDefaultCredentials( ?callable $authHttpHandler = null, ?array $authCacheOptions = null, ?CacheItemPoolInterface $authCache = null, - $quotaProject = null, + ?string $quotaProject = null, ?array $defaultScopes = null, bool $enableRegionalAccessBoundary = true, - ) { + ): FetchAuthTokenInterface { try { return ApplicationDefaultCredentials::getCredentials( $scopes, @@ -333,7 +305,7 @@ private static function buildApplicationDefaultCredentials( /** * @param mixed $token */ - private static function isValid($token) + private static function isValid(mixed $token): bool { return is_array($token) && array_key_exists('access_token', $token); @@ -342,7 +314,7 @@ private static function isValid($token) /** * @param mixed $token */ - private static function isExpired($token) + private static function isExpired(mixed $token): bool { return !(self::isValid($token) && array_key_exists('expires_at', $token) diff --git a/Gax/src/FixedSizeCollection.php b/Gax/src/FixedSizeCollection.php index 13d4f3219cc2..94549f760a6e 100644 --- a/Gax/src/FixedSizeCollection.php +++ b/Gax/src/FixedSizeCollection.php @@ -46,8 +46,9 @@ */ class FixedSizeCollection implements IteratorAggregate { - private $collectionSize; - private $pageList; + private int $collectionSize; + /** @var Page[] */ + private array $pageList; /** * FixedSizeCollection constructor. @@ -81,7 +82,7 @@ public function __construct(Page $initialPage, int $collectionSize) * * @return int */ - public function getCollectionSize() + public function getCollectionSize(): int { $size = 0; foreach ($this->pageList as $page) { @@ -96,7 +97,7 @@ public function getCollectionSize() * * @return bool */ - public function hasNextCollection() + public function hasNextCollection(): bool { return $this->getLastPage()->hasNextPage(); } @@ -107,7 +108,7 @@ public function hasNextCollection() * * @return string */ - public function getNextPageToken() + public function getNextPageToken(): string { return $this->getLastPage()->getNextPageToken(); } @@ -117,7 +118,7 @@ public function getNextPageToken() * * @return FixedSizeCollection */ - public function getNextCollection() + public function getNextCollection(): self { $lastPage = $this->getLastPage(); $nextPage = $lastPage->getNextPage($this->collectionSize); @@ -129,8 +130,7 @@ public function getNextCollection() * * @return Generator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): Generator { foreach ($this->pageList as $page) { foreach ($page as $element) { @@ -144,9 +144,9 @@ public function getIterator() * and making API calls as required until all of the elements have * been retrieved. * - * @return Generator|FixedSizeCollection[] + * @return Generator */ - public function iterateCollections() + public function iterateCollections(): Generator { $currentCollection = $this; yield $this; @@ -156,7 +156,7 @@ public function iterateCollections() } } - private function getLastPage() + private function getLastPage(): Page { $pageList = $this->pageList; // Get last element in array... @@ -170,7 +170,7 @@ private function getLastPage() * @param int $collectionSize * @return Page[] */ - private static function createPageArray(Page $initialPage, int $collectionSize) + private static function createPageArray(Page $initialPage, int $collectionSize): array { $pageList = [$initialPage]; $currentPage = $initialPage; diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index 74516159a8ce..be1861e5adfc 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -53,7 +53,6 @@ use Google\Auth\FetchAuthTokenInterface; use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; -use Google\LongRunning\OperationsClient; use Google\Protobuf\Internal\Message; use GuzzleHttp\Promise\PromiseInterface; @@ -87,7 +86,6 @@ trait GapicClientTrait Call::CLIENT_STREAMING_CALL => 'startClientStreamingCall', Call::SERVER_STREAMING_CALL => 'startServerStreamingCall', ]; - private bool $backwardsCompatibilityMode; /** * Add a middleware to the call stack by providing a callable which will be @@ -177,7 +175,7 @@ public static function getServiceScopes(): array * * @experimental */ - public function close() + public function close(): void { $this->transport->close(); } @@ -187,9 +185,9 @@ public function close() * use by customized clients. * * @access private - * @return TransportInterface + * @return ?TransportInterface */ - protected function getTransport() + protected function getTransport(): ?TransportInterface { return $this->transport; } @@ -199,9 +197,9 @@ protected function getTransport() * use by customized clients. * * @access private - * @return CredentialsWrapper + * @return ?HeaderCredentialsInterface */ - protected function getCredentialsWrapper() + protected function getCredentialsWrapper(): ?HeaderCredentialsInterface { return $this->credentialsWrapper; } @@ -223,14 +221,11 @@ protected function getCredentialsWrapper() * path to a JSON file, or a PHP array containing the decoded JSON data. * By default this settings points to the default client config file, which is provided * in the resources folder. - * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * @type FetchAuthTokenInterface|HeaderCredentialsInterface $credentials * The credentials to be used by the client to authorize API calls. This option - * accepts either a path to a credentials file, or a decoded credentials file as a - * PHP array. - * *Advanced usage*: In addition, this option can also accept a pre-constructed - * \Google\Auth\FetchAuthTokenInterface object or \Google\ApiCore\CredentialsWrapper - * object. Note that when one of these objects are provided, any settings in - * $authConfig will be ignored. + * accepts a pre-constructed \Google\Auth\FetchAuthTokenInterface object or + * \Google\ApiCore\HeaderCredentialsInterface object. Note that when one of these + * objects are provided, any settings in $authConfig will be ignored. * @type array $credentialsConfig * Options used to configure credentials, including auth token caching, for the client. * For a full list of supporting configuration options, see @@ -269,12 +264,8 @@ protected function getCredentialsWrapper() * } * @throws ValidationException */ - private function setClientOptions(array $options) + private function setClientOptions(array $options): void { - // serviceAddress is now deprecated and acts as an alias for apiEndpoint - if (isset($options['serviceAddress'])) { - $options['apiEndpoint'] = $this->pluck('serviceAddress', $options, false); - } self::validateNotNull($options, [ 'apiEndpoint', 'serviceName', @@ -297,7 +288,6 @@ private function setClientOptions(array $options) // Therefore, we need to remove it from the $options array before // creating the ClientOptions. $hasEmulator = $this->pluck('hasEmulator', $options, false) ?? false; - // cast to ClientOptions for new surfaces only $options = new ClientOptions($options); $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( @@ -378,17 +368,11 @@ private function setClientOptions(array $options) */ private function createTransport( string $apiEndpoint, - $transport, - $transportConfig, + string $transport, + TransportOptions|array $transportConfig, ?callable $clientCertSource = null, bool $hasEmulator = false - ) { - if (!is_string($transport)) { - throw new ValidationException( - "'transport' must be a string, instead got:" . - print_r($transport, true) - ); - } + ): TransportInterface { $supportedTransports = self::supportedTransports(); if (!in_array($transport, $supportedTransports)) { throw new ValidationException(sprintf( @@ -461,14 +445,14 @@ private function createOperationsClient(array $options) /** * @return string */ - private static function defaultTransport() + private static function defaultTransport(): string { return self::getGrpcDependencyStatus() ? 'grpc' : 'rest'; } - private function validateCallConfig(string $methodName) + private function validateCallConfig(string $methodName): array { // Ensure a method descriptor exists for the target method. if (!isset($this->descriptors[$methodName])) { @@ -489,8 +473,8 @@ private function validateCallConfig(string $methodName) throw new ValidationException("Requested method '$methodName' does not have a longRunning config " . 'in descriptor configuration.'); } - // @TODO: check if the client implements `OperationsClientInterface` instead - if (!method_exists($this, 'getOperationsClient')) { + if (!$this instanceof LongRunningOperationProviderInterface + && !method_exists($this, 'getOperationsClient')) { throw new ValidationException('Client missing required getOperationsClient ' . "for longrunning call '$methodName'"); } @@ -533,7 +517,7 @@ private function startAsyncCall( string $methodName, Message $request, array $optionalArgs = [] - ) { + ): PromiseInterface { // Convert method name to the UpperCamelCase of RPC names from lowerCamelCase of GAPIC method names // in order to find the method in the descriptor config. $methodName = ucfirst($methodName); @@ -576,13 +560,13 @@ private function startAsyncCall( * * @experimental * - * @return PromiseInterface|PagedListResponse|BidiStream|ClientStream|ServerStream + * @return PromiseInterface|PagedListResponse|BidiStream|ClientStream|ServerStream|ResumableUpload */ private function startApiCall( string $methodName, ?Message $request = null, array $optionalArgs = [] - ) { + ): PromiseInterface|PagedListResponse|BidiStream|ClientStream|ServerStream|ResumableUpload { $methodDescriptors = $this->validateCallConfig($methodName); $callType = $methodDescriptors['callType']; @@ -649,7 +633,7 @@ private function startCall( ?Message $request = null, int $callType = Call::UNARY_CALL, ?string $interfaceName = null - ) { + ): PromiseInterface|BidiStream|ClientStream|ServerStream { $optionalArgs = $this->configureCallOptions($optionalArgs); $callStack = $this->createCallStack( $this->configureCallConstructionOptions($methodName, $optionalArgs) @@ -692,7 +676,7 @@ private function startCall( * * @return callable */ - private function createCallStack(array $callConstructionOptions) + private function createCallStack(array $callConstructionOptions): callable { $fixedHeaders = $this->agentHeader; if ($quotaProject = $this->credentialsWrapper->getQuotaProject()) { @@ -750,7 +734,7 @@ private function createCallStack(array $callConstructionOptions) * * @return array */ - private function configureCallConstructionOptions(string $methodName, array $optionalArgs) + private function configureCallConstructionOptions(string $methodName, array $optionalArgs): array { $retrySettings = $this->retrySettings[$methodName]; $autoPopulatedFields = $this->descriptors[$methodName]['autoPopulatedFields'] ?? []; @@ -775,7 +759,6 @@ private function configureCallConstructionOptions(string $methodName, array $opt */ private function configureCallOptions(array $optionalArgs): array { - // cast to CallOptions for new surfaces only return (new CallOptions($optionalArgs))->toArray(); } @@ -800,10 +783,10 @@ private function startOperationsCall( string $methodName, array $optionalArgs, Message $request, - $client, + object $client, ?string $interfaceName = null, ?string $operationClass = null - ) { + ): PromiseInterface { $optionalArgs = $this->configureCallOptions($optionalArgs); $callStack = $this->createCallStack( $this->configureCallConstructionOptions($methodName, $optionalArgs) @@ -858,7 +841,7 @@ private function getPagedListResponse( string $decodeType, Message $request, ?string $interfaceName = null - ) { + ): PagedListResponse { return $this->getPagedListResponseAsync( $methodName, $optionalArgs, @@ -883,7 +866,7 @@ private function startResumableUploadCall( string $decodeType, ?Message $request, ?string $interfaceName = null - ) { + ): ResumableUpload { if (isset($this->retrySettings[$methodName])) { $callConstructionOptions = $this->configureCallConstructionOptions($methodName, $optionalArgs); $optionalArgs['retrySettings'] = $callConstructionOptions['retrySettings']; @@ -921,7 +904,7 @@ private function getPagedListResponseAsync( string $decodeType, Message $request, ?string $interfaceName = null - ) { + ): PromiseInterface { $optionalArgs = $this->configureCallOptions($optionalArgs); $callStack = $this->createCallStack( $this->configureCallConstructionOptions($methodName, $optionalArgs) @@ -951,7 +934,7 @@ private function getPagedListResponseAsync( * * @return string */ - private function buildMethod(?string $interfaceName = null, ?string $methodName = null) + private function buildMethod(?string $interfaceName = null, ?string $methodName = null): string { return sprintf( '%s/%s', @@ -966,7 +949,7 @@ private function buildMethod(?string $interfaceName = null, ?string $methodName * * @return array */ - private function buildRequestParamsHeader(array $headerParams, ?Message $request = null) + private function buildRequestParamsHeader(array $headerParams, ?Message $request = null): array { $headers = []; @@ -1022,7 +1005,7 @@ private function buildRequestParamsHeader(array $headerParams, ?Message $request /** * The SERVICE_ADDRESS constant is set by GAPIC clients */ - private static function getDefaultAudience() + private static function getDefaultAudience(): ?string { if (!defined('self::SERVICE_ADDRESS')) { return null; diff --git a/Gax/src/HeaderCredentialsInterface.php b/Gax/src/HeaderCredentialsInterface.php index c4a4032db8a1..b41b42402462 100644 --- a/Gax/src/HeaderCredentialsInterface.php +++ b/Gax/src/HeaderCredentialsInterface.php @@ -33,7 +33,9 @@ */ namespace Google\ApiCore; -interface HeaderCredentialsInterface +use Google\Auth\GetQuotaProjectInterface; + +interface HeaderCredentialsInterface extends GetQuotaProjectInterface { /** * @param string|null $audience optional audience for self-signed JWTs. diff --git a/Gax/src/IamProviderInterface.php b/Gax/src/IamProviderInterface.php new file mode 100644 index 000000000000..5a55183e0c99 --- /dev/null +++ b/Gax/src/IamProviderInterface.php @@ -0,0 +1,53 @@ +operationName = $operationName; $this->operationsClient = $operationsClient; @@ -177,7 +175,7 @@ public function __construct(string $operationName, $operationsClient, array $opt * * @return bool */ - public function isDone() + public function isDone(): bool { if (!$this->hasProtoResponse()) { return false; @@ -197,7 +195,7 @@ public function isDone() * * @return bool */ - public function operationSucceeded() + public function operationSucceeded(): bool { if (!$this->hasProtoResponse()) { return false; @@ -218,7 +216,7 @@ public function operationSucceeded() * * @return bool */ - public function operationFailed() + public function operationFailed(): bool { return $this->hasErrors(); } @@ -226,9 +224,9 @@ public function operationFailed() /** * Get the formatted name of the operation * - * @return string The formatted name of the operation + * @return string|null The formatted name of the operation */ - public function getName() + public function getName(): ?string { return $this->operationName; } @@ -253,7 +251,7 @@ public function getName() * @throws ValidationException * @return bool Indicates if the operation completed. */ - public function pollUntilComplete(array $options = []) + public function pollUntilComplete(array $options = []): bool { if ($this->isDone()) { return true; @@ -272,7 +270,7 @@ public function pollUntilComplete(array $options = []) * @throws ApiException If the API call fails. * @throws ValidationException If called on a deleted operation. */ - public function reload() + public function reload(): void { if ($this->deleted) { throw new ValidationException('Cannot call reload() on a deleted operation'); @@ -290,7 +288,7 @@ public function reload() * * @return T|null */ - public function getResult() + public function getResult(): mixed { if (!$this->hasProtoResponse()) { return null; @@ -322,10 +320,10 @@ public function getResult() /** * If the operation failed, return the status. If operationFailed() is false, return null. * - * @return Status|null The status of the operation in case of failure, or null if + * @return Status|Message|null The status of the operation in case of failure, or null if * operationFailed() is false. */ - public function getError() + public function getError(): ?Message { if (!$this->hasProtoResponse() || !$this->isDone()) { return null; @@ -358,7 +356,7 @@ public function getError() * * @return array */ - public function getDescriptorOptions() + public function getDescriptorOptions(): array { return [ 'operationReturnType' => $this->operationReturnType, @@ -367,18 +365,18 @@ public function getDescriptorOptions() } /** - * @return Operation|mixed|null The last Operation object received from the server. + * @return Operation|object|null The last Operation object received from the server. */ - public function getLastProtoResponse() + public function getLastProtoResponse(): ?object { return $this->lastProtoResponse; } /** - * @return object The OperationsClient object used to make + * @return object|null The OperationsClient object used to make * requests to the operations API. */ - public function getOperationsClient() + public function getOperationsClient(): ?object { return $this->operationsClient; } @@ -400,7 +398,7 @@ public function getOperationsClient() * @throws ApiException If the API call fails. * @throws LogicException If the API call method has not been configured */ - public function cancel() + public function cancel(): void { if (is_null($this->cancelOperationMethod)) { throw new LogicException('The cancel operation is not supported by this API'); @@ -420,7 +418,7 @@ public function cancel() * @throws ApiException If the API call fails. * @throws LogicException If the API call method has not been configured */ - public function delete() + public function delete(): void { if (is_null($this->deleteOperationMethod)) { throw new LogicException('The delete operation is not supported by this API'); @@ -437,7 +435,7 @@ public function delete() * * @return mixed The metadata returned from the server in the last response. */ - public function getMetadata() + public function getMetadata(): mixed { if (!$this->hasProtoResponse()) { return null; @@ -457,10 +455,6 @@ public function getMetadata() if (is_null($any)) { return null; } - // @TODO: This is probably not doing anything and can be removed in the next release. - if (is_null($any->getValue())) { - return null; - } $metadataReturnType = $this->metadataReturnType; /** @var Message $metadata */ $metadata = new $metadataReturnType(); @@ -475,7 +469,7 @@ public function getMetadata() * @param string $requestClass The request class to use for the call. * Will be null for legacy operations clients. */ - private function operationsCall(string $method, string $requestClass) + private function operationsCall(string $method, string $requestClass): mixed { if (!method_exists($requestClass, 'build')) { throw new LogicException('Request class must support the static build method'); @@ -490,14 +484,14 @@ private function operationsCall(string $method, string $requestClass) return $this->operationsClient->$method($request); } - private function canHaveResult() + private function canHaveResult(): bool { // The call to getResponse is only for OnePlatform LROs, and is not // supported by other LRO GAPIC clients (e.g. Compute) return method_exists($this->lastProtoResponse, 'getResponse'); } - private function hasErrors() + private function hasErrors(): bool { if (!$this->hasProtoResponse()) { return false; @@ -516,7 +510,7 @@ private function hasErrors() throw new LogicException('Unable to determine operation error status for this service'); } - private function hasProtoResponse() + private function hasProtoResponse(): bool { return !is_null($this->lastProtoResponse); } diff --git a/Gax/src/Options/CallOptions.php b/Gax/src/Options/CallOptions.php index e39eb2563826..ae76b58effca 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -35,7 +35,6 @@ namespace Google\ApiCore\Options; use ArrayAccess; -use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\RetrySettings; /** @@ -54,12 +53,12 @@ class CallOptions implements ArrayAccess, OptionsInterface private ?int $timeoutMillis; private array $transportOptions; private ?array $middlewareOptions; + private ?string $audience; /** @var callable|null $metadataCallback */ private $metadataCallback; - /** @var RetrySettings|array|null $retrySettings */ - private $retrySettings; + private RetrySettings|array|null $retrySettings; /** * @param array $options { @@ -96,6 +95,9 @@ private function fromArray(array $arr): void $this->setRetrySettings($arr['retrySettings'] ?? null); $this->setMetadataCallback($arr['metadataCallback'] ?? null); $this->setMiddlewareOptions($arr['middlewareOptions'] ?? null); + if (isset($arr['audience'])) { + $this->setAudience($arr['audience']); + } } /** @@ -149,7 +151,7 @@ public function setTransportOptions(array $transportOptions): self * * @return $this */ - public function setRetrySettings($retrySettings): self + public function setRetrySettings(RetrySettings|array|null $retrySettings): self { $this->retrySettings = $retrySettings; @@ -174,4 +176,11 @@ public function setMetadataCallback(callable|null $metadataCallback): self return $this; } + + public function setAudience(?string $audience): self + { + $this->audience = $audience; + + return $this; + } } diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 994bbc81b884..825e2c54f7b1 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -36,7 +36,7 @@ use ArrayAccess; use Closure; -use Google\ApiCore\CredentialsWrapper; +use Google\ApiCore\HeaderCredentialsInterface; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; use InvalidArgumentException; @@ -49,11 +49,11 @@ * client constructor: * * ``` - * use Google\ApiCore\ClientOptions; + * use Google\ApiCore\Options\ClientOptions; * use Google\Cloud\SecretManager\Client\SecretManagerClient; * * $options = new ClientOptions([ - * 'credentials' => '/path/to/my/credentials.json' + * 'apiEndpoint' => 'my-custom-endpoint.com' * ]); * $secretManager = new SecretManagerClient($options->toArray()); * ``` @@ -71,13 +71,11 @@ class ClientOptions implements ArrayAccess, OptionsInterface private array $clientConfig; - /** @var string|array|FetchAuthTokenInterface|CredentialsWrapper|null */ - private $credentials; + private FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials; private array $credentialsConfig; - /** @var string|TransportInterface|null $transport */ - private $transport; + private string|TransportInterface|null $transport; private TransportOptions $transportConfig; @@ -114,22 +112,10 @@ class ClientOptions implements ArrayAccess, OptionsInterface * path to a JSON file, or a PHP array containing the decoded JSON data. * By default this settings points to the default client config file, which is provided * in the resources folder. - * @type FetchAuthTokenInterface|CredentialsWrapper $credentials + * @type FetchAuthTokenInterface|HeaderCredentialsInterface $credentials * This option should only be used with a pre-constructed \Google\Auth\FetchAuthTokenInterface - * object or \Google\ApiCore\CredentialsWrapper object. Note that when one of these objects + * object or \Google\ApiCore\HeaderCredentialsInterface object. Note that when one of these objects * are provided, any settings in $authConfig will be ignored. - * **Important**: If you are providing a path to a credentials file, or a decoded credentials - * file as a PHP array, this usage is now DEPRECATED. Providing an unvalidated credential - * configuration to Google APIs can compromise the security of your systems and data. It is now - * recommended to create the credentials explicitly: - * ``` - * use Google\Auth\Credentials\ServiceAccountCredentials; - * use Google\ApiCore\Options\ClientOptions; - * $creds = new ServiceAccountCredentials($scopes, $json); - * $options = new ClientOptions(['credentials' => $creds]); - * ``` - * For more information - * {@see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials} * @type array $credentialsConfig * Options used to configure credentials, including auth token caching, for the client. * For a full list of supporting configuration options, see @@ -232,27 +218,24 @@ public function setDisableRetries(bool $disableRetries): self * @param string|array $clientConfig * * @return $this - * @throws InvalidArgumentException */ - public function setClientConfig($clientConfig): self + public function setClientConfig(string|array $clientConfig): self { if (is_string($clientConfig)) { $this->clientConfig = json_decode(file_get_contents($clientConfig), true); - } elseif (is_array($clientConfig)) { - $this->clientConfig = $clientConfig; } else { - throw new InvalidArgumentException('Invalid client config'); + $this->clientConfig = $clientConfig; } return $this; } /** - * @param string|array|FetchAuthTokenInterface|CredentialsWrapper|null $credentials + * @param FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * * @return $this */ - public function setCredentials($credentials): self + public function setCredentials(FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials): self { $this->credentials = $credentials; @@ -276,7 +259,7 @@ public function setCredentialsConfig(array $credentialsConfig): self * * @return $this */ - public function setTransport($transport): self + public function setTransport(string|TransportInterface|null $transport): self { $this->transport = $transport; diff --git a/Gax/src/Page.php b/Gax/src/Page.php index 8609faccd514..eb083eae3f13 100644 --- a/Gax/src/Page.php +++ b/Gax/src/Page.php @@ -46,14 +46,15 @@ class Page implements IteratorAggregate { const FINAL_PAGE_TOKEN = ''; - private $call; + private Call $call; + /** @var callable */ private $callable; - private $options; - private $pageStreamingDescriptor; + private array $options; + private PageStreamingDescriptor $pageStreamingDescriptor; - private $pageToken; // @phpstan-ignore-line + private string $pageToken; // @phpstan-ignore-line - private $response; + private Message $response; /** * Page constructor. @@ -87,20 +88,20 @@ public function __construct( * * @return bool */ - public function hasNextPage() + public function hasNextPage(): bool { - return strcmp($this->getNextPageToken(), Page::FINAL_PAGE_TOKEN) != 0; + return strcmp((string) $this->getNextPageToken(), Page::FINAL_PAGE_TOKEN) != 0; } /** * Returns the next page token from the response. * - * @return string + * @return string|null */ - public function getNextPageToken() + public function getNextPageToken(): ?string { $responsePageTokenGetMethod = $this->pageStreamingDescriptor->getResponsePageTokenGetMethod(); - return $this->getResponseObject()->$responsePageTokenGetMethod(); + return $this->response->$responsePageTokenGetMethod(); } /** @@ -112,7 +113,7 @@ public function getNextPageToken() * @throws ApiException if the call to fetch the next page fails. * @return Page */ - public function getNextPage(?int $pageSize = null) + public function getNextPage(?int $pageSize = null): self { if (!$this->hasNextPage()) { throw new ValidationException( @@ -161,10 +162,10 @@ public function getNextPage(?int $pageSize = null) * * @return int */ - public function getPageElementCount() + public function getPageElementCount(): int { $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod(); - return count($this->getResponseObject()->$resourcesGetMethod()); + return count($this->response->$resourcesGetMethod()); } /** @@ -172,11 +173,10 @@ public function getPageElementCount() * * @return Generator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): Generator { $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod(); - $items = $this->getResponseObject()->$resourcesGetMethod(); + $items = $this->response->$resourcesGetMethod(); foreach ($items as $key => $element) { if ($items instanceof MapField) { yield $key => $element; @@ -191,11 +191,11 @@ public function getIterator() * Additional Page objects are retrieved lazily via API calls until * all elements have been retrieved. * - * @return Generator|array + * @return Generator * @throws ValidationException * @throws ApiException */ - public function iteratePages() + public function iteratePages(): Generator { $currentPage = $this; yield $this; @@ -210,7 +210,7 @@ public function iteratePages() * * @return mixed|Message */ - public function getRequestObject() + public function getRequestObject(): mixed { return $this->call->getMessage(); } @@ -218,9 +218,9 @@ public function getRequestObject() /** * Gets the API response object. * - * @return mixed|Message + * @return Message|null */ - public function getResponseObject() + public function getResponseObject(): ?Message { return $this->response; } @@ -241,7 +241,7 @@ public function getResponseObject() * @throws ValidationException if a FixedSizeCollection of the specified size cannot be constructed * @return FixedSizeCollection */ - public function expandToFixedSizeCollection($collectionSize) + public function expandToFixedSizeCollection(int $collectionSize): FixedSizeCollection { if (!$this->pageStreamingDescriptor->requestHasPageSizeField()) { throw new ValidationException( diff --git a/Gax/src/PagedListResponse.php b/Gax/src/PagedListResponse.php index d9229a869129..ddc60d7353ea 100644 --- a/Gax/src/PagedListResponse.php +++ b/Gax/src/PagedListResponse.php @@ -83,7 +83,7 @@ */ class PagedListResponse implements IteratorAggregate { - private $firstPage; + private Page $firstPage; /** * PagedListResponse constructor. @@ -109,7 +109,7 @@ public function __construct( * @return Generator * @throws ValidationException */ - public function iterateAllElements() + public function iterateAllElements(): Generator { return $this->getIterator(); } @@ -123,8 +123,7 @@ public function iterateAllElements() * @return Generator * @throws ValidationException */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): Generator { foreach ($this->iteratePages() as $page) { foreach ($page as $key => $element) { @@ -138,7 +137,7 @@ public function getIterator() * * @return Page */ - public function getPage() + public function getPage(): Page { return $this->firstPage; } @@ -147,10 +146,10 @@ public function getPage() * Returns an iterator over pages of results. The pages are * retrieved lazily from the underlying API. * - * @return Page[] + * @return Generator * @throws ValidationException */ - public function iteratePages() + public function iteratePages(): Generator { return $this->getPage()->iteratePages(); } @@ -170,7 +169,7 @@ public function iteratePages() * @throws ValidationException if a FixedSizeCollection of the specified size cannot be constructed * @return FixedSizeCollection */ - public function expandToFixedSizeCollection(int $collectionSize) + public function expandToFixedSizeCollection(int $collectionSize): FixedSizeCollection { return $this->getPage()->expandToFixedSizeCollection($collectionSize); } @@ -190,9 +189,9 @@ public function expandToFixedSizeCollection(int $collectionSize) * * @param int $collectionSize * @throws ValidationException if a FixedSizeCollection of the specified size cannot be constructed - * @return Generator|FixedSizeCollection[] + * @return Generator */ - public function iterateFixedSizeCollections(int $collectionSize) + public function iterateFixedSizeCollections(int $collectionSize): Generator { return $this->expandToFixedSizeCollection($collectionSize)->iterateCollections(); } diff --git a/Gax/src/PollingTrait.php b/Gax/src/PollingTrait.php index de5a99dac4ae..8967f8fa44f7 100644 --- a/Gax/src/PollingTrait.php +++ b/Gax/src/PollingTrait.php @@ -52,7 +52,7 @@ trait PollingTrait * } * @return bool */ - private function poll(callable $pollCallable, array $options) + private function poll(callable $pollCallable, array $options): bool { $currentPollDelayMillis = $options['initialPollDelayMillis']; $pollDelayMultiplier = $options['pollDelayMultiplier']; @@ -82,7 +82,7 @@ private function poll(callable $pollCallable, array $options) * * @return float Current time in milliseconds */ - protected function getCurrentTimeMillis() + protected function getCurrentTimeMillis(): float { return microtime(true) * 1000.0; } @@ -92,7 +92,7 @@ protected function getCurrentTimeMillis() * * @param int $millis */ - protected function sleepMillis(int $millis) + protected function sleepMillis(int $millis): void { usleep($millis * 1000); } diff --git a/Gax/src/ResourceHelperTrait.php b/Gax/src/ResourceHelperTrait.php index 58c85423d536..2587de5c43b7 100644 --- a/Gax/src/ResourceHelperTrait.php +++ b/Gax/src/ResourceHelperTrait.php @@ -42,8 +42,8 @@ */ trait ResourceHelperTrait { - /** @var array|null */ - private static $templateMap; + /** @var array|null */ + private static ?array $templateMap = null; /** * placeholder for this function like we have in GapicClientTrait @@ -53,16 +53,15 @@ private static function getClientDefaults() return []; } - private static function registerPathTemplates() + private static function registerPathTemplates(): void { $templateConfigPath = self::getClientDefaults()['descriptorsConfigPath']; // self::SERVICE_NAME is a constant set per-client. self::loadPathTemplates($templateConfigPath, self::SERVICE_NAME); } - private static function loadPathTemplates(string $configPath, string $serviceName) + private static function loadPathTemplates(string $configPath, string $serviceName): void { - // TODO: Add void return type hint. if (!is_null(self::$templateMap)) { return; } @@ -75,9 +74,8 @@ private static function loadPathTemplates(string $configPath, string $serviceNam } } - private static function getPathTemplate(string $key) + private static function getPathTemplate(string $key): ?PathTemplate { - // TODO: Add nullable return type reference once PHP 7.1 is minimum. if (is_null(self::$templateMap)) { self::registerPathTemplates(); } diff --git a/Gax/src/ResourceTemplate/RelativeResourceTemplate.php b/Gax/src/ResourceTemplate/RelativeResourceTemplate.php index 8417a6e489a9..1e7d64f6afa0 100644 --- a/Gax/src/ResourceTemplate/RelativeResourceTemplate.php +++ b/Gax/src/ResourceTemplate/RelativeResourceTemplate.php @@ -131,7 +131,7 @@ public function render(array $bindings, bool $urlEncode = false) ); } - $encodedValue = $urlEncode ? self::encodeValue($value) : $value; + $encodedValue = $urlEncode ? self::encodeValue((string) $value) : (string) $value; $literalSegments[] = new Segment( Segment::LITERAL_SEGMENT, $encodedValue, diff --git a/Gax/src/ResumableUpload/ResumableUpload.php b/Gax/src/ResumableUpload/ResumableUpload.php index 5f68a5d3b498..86ef826c2d92 100644 --- a/Gax/src/ResumableUpload/ResumableUpload.php +++ b/Gax/src/ResumableUpload/ResumableUpload.php @@ -1,4 +1,6 @@ false, @@ -393,7 +393,7 @@ public static function constructDefault() * } * @return RetrySettings */ - public function with(array $settings) + public function with(array $settings): self { $existingSettings = [ 'initialRetryDelayMillis' => $this->getInitialRetryDelayMillis(), @@ -419,7 +419,7 @@ public function with(array $settings) * @param int $timeout The timeout in milliseconds to be used as a logical call timeout. * @return array */ - public static function logicalTimeout(int $timeout) + public static function logicalTimeout(int $timeout): array { return [ 'initialRpcTimeoutMillis' => $timeout, @@ -433,7 +433,7 @@ public static function logicalTimeout(int $timeout) /** * @return bool Returns true if retries are enabled, otherwise returns false. */ - public function retriesEnabled() + public function retriesEnabled(): bool { return $this->retriesEnabled; } @@ -442,15 +442,15 @@ public function retriesEnabled() * @return int The timeout of the rpc call to be used if $retriesEnabled is false, * in milliseconds. */ - public function getNoRetriesRpcTimeoutMillis() + public function getNoRetriesRpcTimeoutMillis(): int { return $this->noRetriesRpcTimeoutMillis; } /** - * @return int[] Status codes to retry + * @return array Status codes to retry */ - public function getRetryableCodes() + public function getRetryableCodes(): array { return $this->retryableCodes; } @@ -459,16 +459,16 @@ public function getRetryableCodes() * @return int The initial retry delay in milliseconds. If $this->retriesEnabled() * is false, this setting is unused. */ - public function getInitialRetryDelayMillis() + public function getInitialRetryDelayMillis(): int { return $this->initialRetryDelayMillis; } /** - * @return float The retry delay multiplier. If $this->retriesEnabled() + * @return int|float The retry delay multiplier. If $this->retriesEnabled() * is false, this setting is unused. */ - public function getRetryDelayMultiplier() + public function getRetryDelayMultiplier(): int|float { return $this->retryDelayMultiplier; } @@ -477,7 +477,7 @@ public function getRetryDelayMultiplier() * @return int The maximum retry delay in milliseconds. If $this->retriesEnabled() * is false, this setting is unused. */ - public function getMaxRetryDelayMillis() + public function getMaxRetryDelayMillis(): int { return $this->maxRetryDelayMillis; } @@ -487,16 +487,16 @@ public function getMaxRetryDelayMillis() * is false, this setting is unused - use noRetriesRpcTimeoutMillis to * set the timeout in that case. */ - public function getInitialRpcTimeoutMillis() + public function getInitialRpcTimeoutMillis(): int { return $this->initialRpcTimeoutMillis; } /** - * @return float The rpc timeout multiplier. If $this->retriesEnabled() + * @return int|float The rpc timeout multiplier. If $this->retriesEnabled() * is false, this setting is unused. */ - public function getRpcTimeoutMultiplier() + public function getRpcTimeoutMultiplier(): int|float { return $this->rpcTimeoutMultiplier; } @@ -506,7 +506,7 @@ public function getRpcTimeoutMultiplier() * is false, this setting is unused - use noRetriesRpcTimeoutMillis to * set the timeout in that case. */ - public function getMaxRpcTimeoutMillis() + public function getMaxRpcTimeoutMillis(): int { return $this->maxRpcTimeoutMillis; } @@ -517,7 +517,7 @@ public function getMaxRpcTimeoutMillis() * is false, this setting is unused - use noRetriesRpcTimeoutMillis to * set the timeout in that case. */ - public function getTotalTimeoutMillis() + public function getTotalTimeoutMillis(): int { return $this->totalTimeoutMillis; } @@ -525,7 +525,7 @@ public function getTotalTimeoutMillis() /** * @experimental */ - public function getMaxRetries() + public function getMaxRetries(): int { return $this->maxRetries; } @@ -533,12 +533,12 @@ public function getMaxRetries() /** * @experimental */ - public function getRetryFunction() + public function getRetryFunction(): ?Closure { return $this->retryFunction; } - private static function convertArrayFromSnakeCase(array $settings) + private static function convertArrayFromSnakeCase(array $settings): array { $camelCaseSettings = []; foreach ($settings as $key => $value) { diff --git a/Gax/src/ServerStream.php b/Gax/src/ServerStream.php index c659041c5584..fb63ddf307a3 100644 --- a/Gax/src/ServerStream.php +++ b/Gax/src/ServerStream.php @@ -48,8 +48,8 @@ class ServerStream { use LoggingTrait; - private $call; - private $resourcesGetMethod; + private ServerStreamingCallInterface $call; + private ?string $resourcesGetMethod = null; private null|LoggerInterface $logger; /** @@ -60,7 +60,7 @@ class ServerStream * @param null|LoggerInterface $logger A PSR-3 compliant logger. */ public function __construct( - $serverStreamingCall, + ServerStreamingCallInterface $serverStreamingCall, array $streamingDescriptor = [], null|LoggerInterface $logger = null ) { @@ -76,9 +76,9 @@ public function __construct( * completes. Throws an ApiException if the streaming call failed. * * @throws ApiException - * @return \Generator|mixed + * @return \Generator */ - public function readAll() + public function readAll(): iterable { $resourcesGetMethod = $this->resourcesGetMethod; foreach ($this->call->responses() as $response) { @@ -123,7 +123,7 @@ public function readAll() * * @return ServerStreamingCallInterface */ - public function getServerStreamingCall() + public function getServerStreamingCall(): ServerStreamingCallInterface { return $this->call; } diff --git a/Gax/src/ServiceInterface.php b/Gax/src/ServiceInterface.php new file mode 100644 index 000000000000..75547f57b3d7 --- /dev/null +++ b/Gax/src/ServiceInterface.php @@ -0,0 +1,46 @@ +stream = $stream; } diff --git a/Gax/src/Transport/Rest/RestServerStreamingCall.php b/Gax/src/Transport/Rest/RestServerStreamingCall.php index 56c55ae1d163..5544ff2a0dc3 100644 --- a/Gax/src/Transport/Rest/RestServerStreamingCall.php +++ b/Gax/src/Transport/Rest/RestServerStreamingCall.php @@ -177,7 +177,7 @@ public function getTrailingMetadata() */ public function getPeer() { - return $this->originalRequest->getUri(); + return (string) $this->originalRequest->getUri(); } /** diff --git a/Gax/src/UriTrait.php b/Gax/src/UriTrait.php index 8b3b66722eb6..897f9c699259 100644 --- a/Gax/src/UriTrait.php +++ b/Gax/src/UriTrait.php @@ -50,7 +50,7 @@ trait UriTrait * @param array $query * @return UriInterface */ - public function buildUriWithQuery($uri, array $query) + public function buildUriWithQuery(string|UriInterface $uri, array $query): UriInterface { $query = array_filter($query, function ($v) { return $v !== null; diff --git a/Gax/src/ValidationTrait.php b/Gax/src/ValidationTrait.php index aa6a85e2e7bd..63b1544afb7c 100644 --- a/Gax/src/ValidationTrait.php +++ b/Gax/src/ValidationTrait.php @@ -43,7 +43,7 @@ trait ValidationTrait * @param array $requiredKeys List of keys to check for in $arr * @return array Returns $arr for fluent use */ - public static function validate(array $arr, array $requiredKeys) + public static function validate(array $arr, array $requiredKeys): array { return self::validateImpl($arr, $requiredKeys, true); } @@ -53,12 +53,12 @@ public static function validate(array $arr, array $requiredKeys) * @param array $requiredKeys List of keys to check for in $arr * @return array Returns $arr for fluent use */ - public static function validateNotNull(array $arr, array $requiredKeys) + public static function validateNotNull(array $arr, array $requiredKeys): array { return self::validateImpl($arr, $requiredKeys, false); } - private static function validateImpl($arr, $requiredKeys, $allowNull) + private static function validateImpl(array $arr, array $requiredKeys, bool $allowNull): array { foreach ($requiredKeys as $requiredKey) { $valid = array_key_exists($requiredKey, $arr) @@ -74,7 +74,7 @@ private static function validateImpl($arr, $requiredKeys, $allowNull) * @param string $filePath * @throws ValidationException */ - private static function validateFileExists(string $filePath) + private static function validateFileExists(string $filePath): void { if (!file_exists($filePath)) { throw new ValidationException("Could not find specified file: $filePath"); diff --git a/Gax/src/Version.php b/Gax/src/Version.php index 76839d4748e7..98537611fb88 100644 --- a/Gax/src/Version.php +++ b/Gax/src/Version.php @@ -38,15 +38,12 @@ */ class Version { - /** - * @var ?string - */ - private static $version = null; + private static ?string $version = null; /** * @return string The version of the ApiCore library. */ - public static function getApiCoreVersion() + public static function getApiCoreVersion(): string { if (is_null(self::$version)) { $versionFile = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'VERSION']); @@ -62,7 +59,7 @@ public static function getApiCoreVersion() * @param string $file * @return string */ - public static function readVersionFile(string $file) + public static function readVersionFile(string $file): string { $versionString = file_exists($file) ? (string) file_get_contents($file) diff --git a/Gax/src/Testing/MockGrpcTransport.php b/Gax/tests/Testing/MockGrpcTransport.php similarity index 99% rename from Gax/src/Testing/MockGrpcTransport.php rename to Gax/tests/Testing/MockGrpcTransport.php index 851f48c4e929..1c82f4a2ae08 100644 --- a/Gax/src/Testing/MockGrpcTransport.php +++ b/Gax/tests/Testing/MockGrpcTransport.php @@ -32,7 +32,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -namespace Google\ApiCore\Testing; +namespace Google\ApiCore\Tests\Testing; use Google\ApiCore\Transport\GrpcTransport; use Grpc\ChannelCredentials; diff --git a/Gax/tests/Unit/ClientOptionsTraitTest.php b/Gax/tests/Unit/ClientOptionsTraitTest.php index a5c9d964a57f..8adb06babe81 100644 --- a/Gax/tests/Unit/ClientOptionsTraitTest.php +++ b/Gax/tests/Unit/ClientOptionsTraitTest.php @@ -40,9 +40,6 @@ use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetUniverseDomainInterface; use Google\Auth\Logging\StdOutLogger; -use Grpc\Gcp\ApiConfig; -use Grpc\Gcp\Config; -use InvalidArgumentException; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Log\LogLevel; @@ -84,7 +81,6 @@ public static function getClientDefaults() { return [ 'apiEndpoint' => 'test.address.com:443', - 'gcpApiConfigPath' => __DIR__ . '/testdata/resources/test_service_grpc_config.json', ]; } }; @@ -150,15 +146,10 @@ public function testCreateCredentialsWrapper($auth, $authConfig, $expectedCreden public function createCredentialsWrapperData() { - $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; - $keyFile = json_decode(file_get_contents($keyFilePath), true); - $fetcher = $this->prophesize(FetchAuthTokenInterface::class)->reveal(); $credentialsWrapper = new CredentialsWrapper($fetcher); return [ - [$keyFilePath, [], CredentialsWrapper::build(['keyFile' => $keyFile])], - [$keyFile, [], CredentialsWrapper::build(['keyFile' => $keyFile])], [$fetcher, [], new CredentialsWrapper($fetcher)], [$credentialsWrapper, [], $credentialsWrapper], ]; @@ -182,83 +173,24 @@ public function testCreateCredentialsWrapperFromEnv() $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper); } - - /** - * @dataProvider createCredentialsWrapperValidationExceptionData - */ - public function testCreateCredentialsWrapperValidationException($auth, $authConfig) - { - - $this->expectException(ValidationException::class); - - $this->clientStub->createCredentialsWrapper( - $auth, - $authConfig, - '' - ); - } - - public function createCredentialsWrapperValidationExceptionData() - { - return [ - ['not a json string', []], - [new \stdClass(), []], - ]; - } - - /** - * @dataProvider createCredentialsWrapperInvalidArgumentExceptionData - */ - public function testCreateCredentialsWrapperInvalidArgumentException($auth, $authConfig) - { - - $this->expectException(InvalidArgumentException::class); - - $this->clientStub->createCredentialsWrapper( - $auth, - $authConfig, - '' - ); - } - - public function createCredentialsWrapperInvalidArgumentExceptionData() - { - return [ - [['array' => 'without right keys'], []], - ]; - } - /** * @dataProvider buildClientOptionsProvider */ public function testBuildClientOptions($options, $expectedUpdatedOptions) { - if (!extension_loaded('sysvshm')) { - $this->markTestSkipped('The sysvshm extension must be installed to execute this test.'); - } $updatedOptions = $this->clientStub->buildClientOptions($options); $this->assertEquals($expectedUpdatedOptions, $updatedOptions); } public function buildClientOptionsProvider() { - $apiConfig = new ApiConfig(); - $apiConfig->mergeFromJsonString( - file_get_contents(__DIR__ . '/testdata/resources/test_service_grpc_config.json') - ); - $grpcGcpConfig = new Config('test.address.com:443', $apiConfig); - $defaultOptions = [ 'apiEndpoint' => 'test.address.com:443', - 'gcpApiConfigPath' => __DIR__ . '/testdata/resources/test_service_grpc_config.json', 'disableRetries' => false, 'transport' => null, 'transportConfig' => [ 'grpc' => [ - 'stubOpts' => [ - 'grpc_call_invoker' => $grpcGcpConfig->callInvoker(), - 'grpc.service_config_disable_resolution' => 1, - ], + 'stubOpts' => ['grpc.service_config_disable_resolution' => 1], 'logger' => null, ], 'rest' => [ @@ -316,9 +248,6 @@ public function buildClientOptionsProvider() */ public function testBuildClientOptionsRestOnly($options, $expectedUpdatedOptions) { - if (!extension_loaded('sysvshm')) { - $this->markTestSkipped('The sysvshm extension must be installed to execute this test.'); - } $restOnlyClient = new class() { use ClientOptionsTrait { buildClientOptions as public; diff --git a/Gax/tests/Unit/CredentialsWrapperTest.php b/Gax/tests/Unit/CredentialsWrapperTest.php index 93745532c82f..45c260e7e9f8 100644 --- a/Gax/tests/Unit/CredentialsWrapperTest.php +++ b/Gax/tests/Unit/CredentialsWrapperTest.php @@ -39,7 +39,6 @@ use Google\Auth\Cache\SysVCacheItemPool; use Google\Auth\Credentials\GCECredentials; use Google\Auth\Credentials\ServiceAccountCredentials; -use Google\Auth\CredentialsLoader; use Google\Auth\FetchAuthTokenCache; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GCECache; @@ -69,15 +68,6 @@ public function testBuildWithoutExplicitKeyFile($args, $expectedCredentialsWrapp $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', $appDefaultCreds); } - /** - * @dataProvider buildDataWithKeyFile - */ - public function testBuildWithKeyFile($args, $expectedCredentialsWrapper) - { - $actualCredentialsWrapper = CredentialsWrapper::build($args); - $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper); - } - public function buildDataWithoutExplicitKeyFile() { $appDefaultCreds = getenv('GOOGLE_APPLICATION_CREDENTIALS'); @@ -180,69 +170,6 @@ public function buildDataWithoutExplicitKeyFile() return $testData; } - public function buildDataWithKeyFile() - { - $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; - $keyFile = json_decode(file_get_contents($keyFilePath), true); - - $scopes = ['myscope']; - $authHttpHandler = function () { - }; - $defaultAuthCache = new MemoryCacheItemPool(); - $authCache = new SysVCacheItemPool(); - $authCacheOptions = ['lifetime' => 600]; - $quotaProject = 'my-quota-project'; - return [ - [ - ['keyFile' => $keyFile], - $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null), - ], - [ - ['keyFile' => $keyFilePath], - $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null), - ], - [ - ['keyFile' => $keyFile, 'scopes' => $scopes], - $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, null), - ], - [ - ['keyFile' => $keyFile, 'scopes' => $scopes, 'authHttpHandler' => $authHttpHandler], - $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, $authHttpHandler), - ], - [ - ['keyFile' => $keyFile, 'enableCaching' => false], - $this->makeExpectedKeyFileCreds($keyFile, null, null, null, null), - ], - [ - ['keyFile' => $keyFile, 'authCacheOptions' => $authCacheOptions], - $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, $authCacheOptions, null), - ], - [ - ['keyFile' => $keyFile, 'authCache' => $authCache], - $this->makeExpectedKeyFileCreds($keyFile, null, $authCache, null, null), - ], - [ - ['keyFile' => $keyFile, 'quotaProject' => $quotaProject], - $this->makeExpectedKeyFileCreds( - $keyFile + ['quota_project_id' => $quotaProject], - null, - $defaultAuthCache, - null, - null - ), - ], - ]; - } - - private function makeExpectedKeyFileCreds($keyFile, $scopes, $cache, $cacheConfig, $httpHandler) - { - $loader = CredentialsLoader::makeCredentials($scopes, $keyFile); - if ($cache) { - $loader = new FetchAuthTokenCache($loader, $cacheConfig, $cache); - } - return new CredentialsWrapper($loader, $httpHandler); - } - /** * @dataProvider provideCheckUniverseDomainFails */ @@ -575,11 +502,14 @@ public function testGetProjectIdWithFetchAuthTokenCache() public function testSerializeCredentialsWrapper() { - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json', - ]); + $appDefaultCreds = getenv('GOOGLE_APPLICATION_CREDENTIALS'); + $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', __DIR__ . '/testdata/creds/json-key-file.json'); + + $credentialsWrapper = CredentialsWrapper::build(); $serialized = serialize($credentialsWrapper); $this->assertIsString($serialized); + + $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', $appDefaultCreds); } private function setEnv(string $env, ?string $value = null) diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 1edc719ccb65..2ee00cbdb0b0 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -39,7 +39,8 @@ use Google\ApiCore\ClientStream; use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\GapicClientTrait; -use Google\ApiCore\LongRunning\OperationsClient; +use Google\ApiCore\HeaderCredentialsInterface; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\OperationResponse; use Google\ApiCore\RequestParamsHeaderDescriptor; @@ -54,8 +55,8 @@ use Google\ApiCore\Transport\TransportInterface; use Google\ApiCore\ValidationException; use Google\Auth\FetchAuthTokenInterface; +use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; -use Grpc\Gcp\Config; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Promise\PromiseInterface; use PHPUnit\Framework\TestCase; @@ -68,6 +69,11 @@ class GapicClientTraitTest extends TestCase use ProphecyTrait; use TestTrait; + public static function setUpBeforeClass(): void + { + self::autoloadTestdata('mocks', 'Google'); + } + public function setUp(): void { $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; @@ -114,14 +120,16 @@ public function testHeadersOverwriteBehavior() 'x-goog-request-params' => ['name=foos%2F123%2Fbars%2F456'] ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $transport->startUnaryCall( Argument::type(Call::class), [ 'headers' => $expectedHeaders, 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -130,7 +138,7 @@ public function testHeadersOverwriteBehavior() $client->set('agentHeader', $header); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -163,15 +171,13 @@ public function testMiddlewareOptionsIsPreservedByFilterAndVisibleToMiddlewares( ->shouldBeCalledOnce() ->willReturn($this->prophesize(PromiseInterface::class)->reveal()); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $client = new StubGapicClient(); $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -230,20 +236,14 @@ public function testMiddlewareOptionsPreservedByCallOptionsOnNewSurface() ->shouldBeCalledOnce() ->willReturn($this->prophesize(PromiseInterface::class)->reveal()); - $credentialsWrapper = CredentialsWrapper::build([ - "keyFile" => __DIR__ . "/testdata/creds/json-key-file.json" - ]); + $credentialsWrapper = CredentialsWrapper::build(); - $client = new class extends StubGapicClient { - protected function isNewClientSurface(): bool { - return true; - } - }; + $client = new StubGapicClient(); $client->set("agentHeader", []); $client->set( "retrySettings", - ["method" => $this->prophesize(RetrySettings::class)->reveal()] + ["method" => RetrySettings::constructDefault()] ); $client->set("transport", $transport->reveal()); $client->set("credentialsWrapper", $credentialsWrapper); @@ -302,14 +302,16 @@ public function testVersionedHeadersOverwriteBehavior() 'x-goog-request-params' => ['name=foos%2F123%2Fbars%2F456'], ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $transport->startUnaryCall( Argument::type(Call::class), [ 'headers' => $expectedHeaders, 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -318,7 +320,7 @@ public function testVersionedHeadersOverwriteBehavior() $client->set('agentHeader', $header); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); @@ -376,7 +378,7 @@ public function testConfigureCallConstructionOptionsAcceptsRetryObjectOrArray() public function testStartOperationsCall() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'longRunning' => [ 'operationReturnType' => 'operationType', @@ -397,7 +399,7 @@ public function testStartOperationsCall() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $message = new MockRequest(); $operationsClient = $this->prophesize(OperationsClient::class); @@ -421,7 +423,7 @@ public function testStartOperationsCall() public function testStartApiCallOperation() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'callType' => Call::LONGRUNNING_CALL, @@ -444,7 +446,7 @@ public function testStartApiCallOperation() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $operationsClient = $this->prophesize(OperationsClient::class); $client->set('operationsClient', $operationsClient->reveal()); @@ -467,7 +469,7 @@ public function testStartApiCallOperation() public function testStartApiCallCustomOperation() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'callType' => Call::LONGRUNNING_CALL, @@ -491,7 +493,7 @@ public function testStartApiCallCustomOperation() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $longRunningDescriptors]); $operationsClient = $this->prophesize(OperationsClient::class)->reveal(); $client->set('operationsClient', $operationsClient); @@ -573,7 +575,7 @@ public function startApiCallExceptions() public function testStartApiCallUnary() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $unaryDescriptors = [ 'callType' => Call::UNARY_CALL, 'responseType' => 'Google\Longrunning\Operation', @@ -594,7 +596,7 @@ public function testStartApiCallUnary() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $unaryDescriptors]); $request = new MockRequest(); @@ -607,7 +609,7 @@ public function testStartApiCallUnary() public function testStartApiCallPaged() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $pagedDescriptors = [ 'callType' => Call::PAGINATED_CALL, 'responseType' => 'Google\Longrunning\ListOperationsResponse', @@ -630,7 +632,7 @@ public function testStartApiCallPaged() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['method' => $retrySettings]); $client->set('descriptors', ['method' => $pagedDescriptors]); $request = new MockRequest(); @@ -643,7 +645,7 @@ public function testStartApiCallPaged() public function testStartAsyncCall() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $unaryDescriptors = [ 'callType' => Call::UNARY_CALL, 'responseType' => 'Google\Longrunning\Operation' @@ -658,7 +660,7 @@ public function testStartAsyncCall() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['Method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['Method' => $retrySettings]); $client->set('descriptors', ['Method' => $unaryDescriptors]); $request = new MockRequest(); @@ -671,7 +673,7 @@ public function testStartAsyncCall() public function testStartAsyncCallPaged() { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $pagedDescriptors = [ 'callType' => Call::PAGINATED_CALL, 'responseType' => 'Google\Longrunning\ListOperationsResponse', @@ -700,7 +702,7 @@ public function testStartAsyncCallPaged() $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); - $client->set('retrySettings', ['Method' => $retrySettings->reveal()]); + $client->set('retrySettings', ['Method' => $retrySettings]); $client->set('descriptors', ['Method' => $pagedDescriptors]); $request = new MockRequest(); @@ -846,34 +848,11 @@ public function createTransportDataInvalid() ], ]; return [ - [$apiEndpoint, null, $transportConfig], - [$apiEndpoint, ['transport' => 'weirdstring'], $transportConfig], - [$apiEndpoint, ['transport' => new \stdClass()], $transportConfig], - [$apiEndpoint, ['transport' => 'rest'], []], + [$apiEndpoint, 'weirdstring', $transportConfig], + [$apiEndpoint, 'rest', []], ]; } - public function testServiceAddressAlias() - { - $client = new StubGapicClient(); - $apiEndpoint = 'test.address.com:443'; - $updatedOptions = $client->buildClientOptions( - ['serviceAddress' => $apiEndpoint] - ); - $client->setClientOptions($updatedOptions); - - $this->assertEquals($apiEndpoint, $updatedOptions['apiEndpoint']); - $this->assertArrayNotHasKey('serviceAddress', $updatedOptions); - } - - public function testOperationClientClassOption() - { - $options = ['operationsClientClass' => CustomOperationsClient::class]; - $client = new StubGapicClient(); - $operationsClient = $client->createOperationsClient($options); - $this->assertInstanceOf(CustomOperationsClient::class, $operationsClient); - } - public function testAdditionalArgumentMethods() { $client = new StubGapicClient(); @@ -881,6 +860,7 @@ public function testAdditionalArgumentMethods() // Set the LRO descriptors we are testing. $longRunningDescriptors = [ 'longRunning' => [ + 'getOperationRequest' => \Google\CustomOperation\GetOperationRequest::class, 'additionalArgumentMethods' => [ 'getPageToken', 'getPageSize', @@ -900,7 +880,6 @@ public function testAdditionalArgumentMethods() // Set up things for the mock call to work. $client->set('credentialsWrapper', CredentialsWrapper::build([])); $client->set('agentHeader', []); - $retrySettings = $this->prophesize(RetrySettings::class); $client->set('retrySettings', [ 'method.name' => RetrySettings::constructDefault() ]); @@ -915,7 +894,9 @@ public function testAdditionalArgumentMethods() // Create mock operations client to test the additional arguments from // the request object are used. $operationsClient = $this->prophesize(CustomOperationsClient::class); - $operationsClient->getOperation('test-123', 'abc', 100) + $operationsClient->getOperation( + \Google\CustomOperation\GetOperationRequest::build('abc', 100, 'test-123') + ) ->shouldBeCalledOnce(); $operationResponse = $client->startOperationsCall( @@ -982,10 +963,13 @@ public function testBuildClientOptionsRegionalEndpoint(?string $apiEndpoint, ?st $client = new class() extends StubGapicClient { public array $capturedCredentialsConfig = []; - public function createCredentialsWrapper($credentials, array $credentialsConfig, string $universeDomain) - { + public function createCredentialsWrapper( + FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + array $credentialsConfig, + string $universeDomain + ): HeaderCredentialsInterface { $this->capturedCredentialsConfig = $credentialsConfig; - return null; + return new InsecureCredentialsWrapper(); } }; @@ -1099,7 +1083,7 @@ public function buildRequestHeaderParams() private function buildClientToTestModifyCallMethods($clientClass = null) { $header = AgentHeader::buildAgentHeader([]); - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $longRunningDescriptors = [ 'longRunning' => [ @@ -1118,21 +1102,19 @@ private function buildClientToTestModifyCallMethods($clientClass = null) ], ]; $transport = $this->prophesize(TransportInterface::class); - $credentialsWrapper = CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]); + $credentialsWrapper = CredentialsWrapper::build(); $clientClass = $clientClass ?: StubGapicClientExtension::class; $client = new $clientClass(); $client->set('transport', $transport->reveal()); $client->set('credentialsWrapper', $credentialsWrapper); $client->set('agentHeader', $header); $client->set('retrySettings', [ - 'simpleMethod' => $retrySettings->reveal(), - 'longRunningMethod' => $retrySettings->reveal(), - 'pagedMethod' => $retrySettings->reveal(), - 'bidiStreamingMethod' => $retrySettings->reveal(), - 'clientStreamingMethod' => $retrySettings->reveal(), - 'serverStreamingMethod' => $retrySettings->reveal(), + 'simpleMethod' => $retrySettings, + 'longRunningMethod' => $retrySettings, + 'pagedMethod' => $retrySettings, + 'bidiStreamingMethod' => $retrySettings, + 'clientStreamingMethod' => $retrySettings, + 'serverStreamingMethod' => $retrySettings, ]); $client->set('descriptors', [ 'longRunningMethod' => $longRunningDescriptors, @@ -1151,9 +1133,10 @@ public function testModifyUnaryCallFromStartCall() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1177,10 +1160,11 @@ public function testModifyUnaryCallFromOperationsCall() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'metadataReturnType' => 'metadataType' + 'credentialsWrapper' => CredentialsWrapper::build(), + 'metadataReturnType' => 'metadataType', + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1205,9 +1189,10 @@ public function testModifyUnaryCallFromGetPagedListResponse() 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1233,9 +1218,10 @@ public function testModifyStreamingCallFromStartCall($callArgs, $expectedMethod, 'custom' => ['addModifyStreamingCallable' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1312,7 +1298,11 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() 'headers' => AgentHeader::buildAgentHeader([]) + [ 'X-Goog-User-Project' => [$quotaProject], ], - 'credentialsWrapper' => $credentialsWrapper->reveal() + 'credentialsWrapper' => $credentialsWrapper->reveal(), + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1327,7 +1317,7 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() $client->setClientOptions($updatedOptions); $client->set( 'retrySettings', - ['method' => $this->prophesize(RetrySettings::class)->reveal()] + ['method' => RetrySettings::constructDefault()] ); $client->startCall( 'method', @@ -1337,7 +1327,7 @@ public function testUserProjectHeaderIsSetWhenProvidingQuotaProject() public function testDefaultAudience() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1348,6 +1338,10 @@ public function testDefaultAudience() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1358,7 +1352,7 @@ public function testDefaultAudience() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->startCall('method.name', 'decodeType'); @@ -1370,6 +1364,10 @@ public function testDefaultAudience() 'audience' => 'custom-audience', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1382,7 +1380,7 @@ public function testDefaultAudience() public function testDefaultAudienceWithOperations() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1393,7 +1391,11 @@ public function testDefaultAudienceWithOperations() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, - 'metadataReturnType' => 'metadataType' + 'metadataReturnType' => 'metadataType', + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1414,7 +1416,7 @@ public function testDefaultAudienceWithOperations() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->set('descriptors', ['method.name' => $longRunningDescriptors]); @@ -1431,7 +1433,7 @@ public function testDefaultAudienceWithOperations() public function testDefaultAudienceWithPagedList() { - $retrySettings = $this->prophesize(RetrySettings::class); + $retrySettings = RetrySettings::constructDefault(); $credentialsWrapper = $this->prophesize(CredentialsWrapper::class) ->reveal(); $transport = $this->prophesize(TransportInterface::class); @@ -1442,6 +1444,10 @@ public function testDefaultAudienceWithPagedList() 'audience' => 'https://service-address/', 'headers' => [], 'credentialsWrapper' => $credentialsWrapper, + 'timeoutMillis' => 30000, + 'transportOptions' => [], + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1461,7 +1467,7 @@ public function testDefaultAudienceWithPagedList() $client->set('agentHeader', []); $client->set( 'retrySettings', - ['method.name' => $retrySettings->reveal()] + ['method.name' => $retrySettings] ); $client->set('transport', $transport->reveal()); $client->set('descriptors', [ @@ -1549,9 +1555,10 @@ public function __invoke(Call $call, array $options) 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1619,9 +1626,10 @@ public function __invoke(Call $call, array $options) 'custom' => ['addModifyUnaryCallableOption' => true] ], 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1685,13 +1693,14 @@ public function __invoke(Call $call, array $options) $transport->startUnaryCall( Argument::type(Call::class), [ - 'transportOptions' => [ - 'custom' => ['addModifyUnaryCallableOption' => true] - ], - 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]) + 'transportOptions' => [ + 'custom' => ['addModifyUnaryCallableOption' => true] + ], + 'headers' => AgentHeader::buildAgentHeader([]), + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, + 'metadataCallback' => null, + 'middlewareOptions' => null, ] ) ->shouldBeCalledOnce() @@ -1707,12 +1716,8 @@ public function __invoke(Call $call, array $options) $this->assertEquals(['middleware2', 'middleware1'], $callOrder); } - public function testInvalidClientOptionsTypeThrowsExceptionForV2SurfaceOnly() + public function testInvalidClientOptionsTypeThrowsException() { - // v1 client - new StubGapicClient(['apiEndpoint' => ['foo']]); - $this->assertTrue(true, 'Test made it to here without throwing an exception'); - $this->expectException(\TypeError::class); $this->expectExceptionMessage( PHP_MAJOR_VERSION < 8 @@ -1722,7 +1727,6 @@ public function testInvalidClientOptionsTypeThrowsExceptionForV2SurfaceOnly() . '($apiEndpoint) must be of type ?string, array given' ); - // v2 client new GapicV2SurfaceClient(['apiEndpoint' => ['foo']]); } @@ -1736,10 +1740,8 @@ public function testCallOptionsForV2Surface() Argument::type(Call::class), [ 'headers' => AgentHeader::buildAgentHeader([]) + ['Foo' => 'Bar'], - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'timeoutMillis' => null, // adds null timeoutMillis, + 'credentialsWrapper' => CredentialsWrapper::build(), + 'timeoutMillis' => 30000, // adds null timeoutMillis, 'transportOptions' => [], 'metadataCallback' => null, 'middlewareOptions' => null, @@ -1761,32 +1763,6 @@ public function testCallOptionsForV2Surface() )->wait(); } - public function testInvalidCallOptionsTypeForV1SurfaceDoesNotThrowException() - { - list($client, $transport) = $this->buildClientToTestModifyCallMethods(); - - $transport->startUnaryCall( - Argument::type(Call::class), - [ - 'transportOptions' => ['custom' => ['addModifyUnaryCallableOption' => true]], - 'headers' => AgentHeader::buildAgentHeader([]), - 'credentialsWrapper' => CredentialsWrapper::build([ - 'keyFile' => __DIR__ . '/testdata/creds/json-key-file.json' - ]), - 'timeoutMillis' => 'blue', // invalid type, this is ignored - ] - ) - ->shouldBeCalledOnce() - ->willReturn(new FulfilledPromise(new Operation())); - - $client->startCall( - 'simpleMethod', - 'decodeType', - ['timeoutMillis' => 'blue'], - new MockRequest(), - )->wait(); - } - public function testInvalidCallOptionsTypeForV2SurfaceThrowsException() { $this->expectException(\TypeError::class); @@ -1896,8 +1872,15 @@ public function testApiKeyOptionAndQuotaProject() public function testHasEmulatorOption() { - $gapic = new class() { + $mockTransport = $this->prophesize(TransportInterface::class)->reveal(); + $gapic = new class($mockTransport) { public bool $hasEmulator; + private TransportInterface $mockTransport; + + public function __construct(TransportInterface $mockTransport) + { + $this->mockTransport = $mockTransport; + } use GapicClientTrait { buildClientOptions as public; @@ -1910,12 +1893,13 @@ public function testHasEmulatorOption() private function createTransport( string $apiEndpoint, - $transport, + string|TransportInterface $transport, $transportConfig, ?callable $clientCertSource = null, bool $hasEmulator = false - ) { + ): TransportInterface { $this->hasEmulator = $hasEmulator; + return $this->mockTransport; } }; @@ -2114,7 +2098,7 @@ public function getOperationsClient() class CustomOperationsClient { - public function getOperation($name, $arg1, $arg2) + public function getOperation($request) { } } diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 4ef50bb3ac77..21715d65ded0 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -527,7 +527,7 @@ public function getSleeps() return $this->sleeps; } - public function sleepMillis(int $millis) + public function sleepMillis(int $millis): void { $this->currentTime += $millis; $this->sleeps[] = $millis; @@ -538,9 +538,9 @@ public function setTimes($times) $this->times = $times; } - public function getCurrentTimeMillis() + public function getCurrentTimeMillis(): float { - return $this->currentTime; + return (float) $this->currentTime; } }; } diff --git a/Gax/tests/Unit/Transport/GrpcTransportTest.php b/Gax/tests/Unit/Transport/GrpcTransportTest.php index f2c69e1f0401..66a0616e1c86 100644 --- a/Gax/tests/Unit/Transport/GrpcTransportTest.php +++ b/Gax/tests/Unit/Transport/GrpcTransportTest.php @@ -35,8 +35,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\Call; use Google\ApiCore\CredentialsWrapper; -use Google\ApiCore\Testing\MockGrpcTransport; use Google\ApiCore\Testing\MockRequest; +use Google\ApiCore\Tests\Testing\MockGrpcTransport; use Google\ApiCore\Tests\Unit\TestTrait; use Google\ApiCore\Transport\GrpcTransport; use Google\ApiCore\ValidationException; @@ -50,7 +50,6 @@ use Grpc\CallInvoker; use Grpc\ChannelCredentials; use Grpc\ClientStreamingCall; -use Grpc\Interceptor; use Grpc\ServerStreamingCall; use Grpc\UnaryCall; use GuzzleHttp\Promise\Promise; @@ -668,13 +667,8 @@ public function interceptorDataProvider() { $this->autoloadTestdata('mocks', __NAMESPACE__); - $deprecatedInterceptors = (new \ReflectionClass(Interceptor::class)) - ->getMethod('interceptUnaryUnary') - ->getParameters()[3] - ->getName() === 'metadata'; - - $interceptor = $deprecatedInterceptors ? new DeprecatedTestInterceptor(): new TestInterceptor(); - $unaryInterceptor = $deprecatedInterceptors ? new DeprecatedTestUnaryInterceptor(): new TestUnaryInterceptor(); + $interceptor = new TestInterceptor(); + $unaryInterceptor = new TestUnaryInterceptor(); return [ [ diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php index 7e2783ccb015..31af507fad80 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/GetOperationRequest.php @@ -6,9 +6,9 @@ class GetOperationRequest { public string $name; public string $arg2; - public string $arg3; + public string|int $arg3; - public static function build(string $arg2, string $arg3, string $name): static + public static function build(string $arg2, string|int $arg3, string $name): static { $request = new static(); $request->name = $name; diff --git a/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php b/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php deleted file mode 100644 index cc625ae4477f..000000000000 --- a/Gax/tests/Unit/testdata/mocks/DeprecatedTestInterceptor.php +++ /dev/null @@ -1,32 +0,0 @@ - true, 'projectId' => 'example-project', - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ] ], [ 'encode', 'requestHandler' @@ -166,7 +166,7 @@ public function testPublisherCompression( [ 'suppressKeyFileNotice' => true, 'projectId' => 'example-project', - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ] ], [ 'encode', 'requestHandler' diff --git a/PubSub/tests/Unit/PubSubClientTest.php b/PubSub/tests/Unit/PubSubClientTest.php index b7340103cd41..63dfc007fda7 100644 --- a/PubSub/tests/Unit/PubSubClientTest.php +++ b/PubSub/tests/Unit/PubSubClientTest.php @@ -17,13 +17,13 @@ namespace Google\Cloud\PubSub\Tests\Unit; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Core\Duration; use Google\Cloud\Core\Exception\BadRequestException; use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\RequestHandler; use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\TestHelpers; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Core\Timestamp; use Google\Cloud\PubSub\Message; use Google\Cloud\PubSub\PubSubClient; @@ -63,7 +63,7 @@ public function setUp(): void [ 'projectId' => self::PROJECT, 'transport' => 'rest', - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ] ], ['requestHandler']); } diff --git a/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php b/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php index 5e0dc0f71e5c..81fa4698eecb 100644 --- a/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php +++ b/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php @@ -32,7 +32,7 @@ namespace Google\Cloud\Spanner\OpenTelemetry; -use Google\ApiCore\CredentialsWrapper; +use Google\ApiCore\HeaderCredentialsInterface; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\HandlerStack; use OpenTelemetry\Contrib\Otlp\MetricExporter as OtlpMetricExporter; @@ -58,13 +58,13 @@ class OtlpMetricsExporter implements PushMetricExporterInterface, AggregationTem private PushMetricExporterInterface $otlpExporter; /** - * @param CredentialsWrapper $credentials The credentials wrapper for metric export. + * @param HeaderCredentialsInterface $credentials The credentials wrapper for metric export. * @param int $timeoutMillis The timeout defined for the metrics client during export. * @param array $options Optional configuration parameters. * @param PushMetricExporterInterface|null $otlpExporter Optional inner exporter for testing. */ public function __construct( - CredentialsWrapper $credentials, + HeaderCredentialsInterface $credentials, int $timeoutMillis = 100, array $options = [], ?PushMetricExporterInterface $otlpExporter = null diff --git a/Spanner/src/SpannerClient.php b/Spanner/src/SpannerClient.php index 9162283b915f..1bcdcea3c8a2 100644 --- a/Spanner/src/SpannerClient.php +++ b/Spanner/src/SpannerClient.php @@ -21,6 +21,7 @@ use Exception; use Google\ApiCore\ClientOptionsTrait; use Google\ApiCore\CredentialsWrapper; +use Google\ApiCore\HeaderCredentialsInterface; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\Options\CallOptions; use Google\ApiCore\ValidationException; @@ -1063,7 +1064,7 @@ private function configureKeepAlive(array $config): array private function configureMetrics( array $options, - string|array|FetchAuthTokenInterface|CredentialsWrapper|null $rawCredentials = null + FetchAuthTokenInterface|HeaderCredentialsInterface|null $rawCredentials = null ): void { $timeoutMillis = $this->pluck('metricsTimeoutMillis', $options, false) ?? 100; @@ -1187,9 +1188,9 @@ private function generateClientHash(string $clientUid): string } private function buildMetricsCredentials( - string|array|FetchAuthTokenInterface|CredentialsWrapper|null $credentials, + FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, array $options - ): CredentialsWrapper { + ): HeaderCredentialsInterface { $credentialsConfig = [ 'scopes' => [ self::MONITORING_WRITE_SCOPE diff --git a/Spanner/tests/Unit/DatabaseTest.php b/Spanner/tests/Unit/DatabaseTest.php index 0872897b3405..c4e340cd2e90 100644 --- a/Spanner/tests/Unit/DatabaseTest.php +++ b/Spanner/tests/Unit/DatabaseTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Spanner\Tests\Unit; use BadMethodCallException; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\OperationResponse; use Google\ApiCore\Page; use Google\ApiCore\PagedListResponse; @@ -32,7 +33,6 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Spanner\Admin\Database\V1\Backup; use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Database\V1\Database as DatabaseProto; @@ -414,7 +414,7 @@ public function testCreate() ->willReturn($this->operationResponse->reveal()); new OperationResponse('my-operation', new DatabaseAdminClient([ - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]), [ 'lastProtoResponse' => $this->serializer->decodeMessage( new DatabaseProto(), diff --git a/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php b/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php index 422a2e8968cd..1a30f2fee841 100644 --- a/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php +++ b/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php @@ -18,11 +18,11 @@ namespace Google\Cloud\Spanner\Tests\Unit; use Google\ApiCore\ApiException; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Spanner\Middleware\RequestIdHeaderMiddleware; use Google\ApiCore\Call; use Google\ApiCore\Transport\TransportInterface; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Spanner\Admin\Instance\V1\ListInstancesResponse; use Google\Cloud\Spanner\SpannerClient; use Google\Rpc\Code; @@ -181,7 +181,7 @@ public function testMiddlewareGetsTheRetryField() $transport = $this->prophesize(TransportInterface::class); $client = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'transport' => $transport->reveal() ]); diff --git a/Spanner/tests/Unit/SpannerClientTest.php b/Spanner/tests/Unit/SpannerClientTest.php index 62e231cac99b..86457a80ed90 100644 --- a/Spanner/tests/Unit/SpannerClientTest.php +++ b/Spanner/tests/Unit/SpannerClientTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Spanner\Tests\Unit; +use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\OperationResponse; use Google\ApiCore\Page; use Google\ApiCore\PagedListResponse; @@ -25,7 +26,6 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\Instance as InstanceProto; @@ -109,7 +109,7 @@ public function setUp(): void ])); $this->spannerClient = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -555,7 +555,7 @@ public function testClientPassesIsolationLevel() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'isolationLevel' => IsolationLevel::REPEATABLE_READ, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), ]); $reflectedClient = new ReflectionClass($client); @@ -589,7 +589,7 @@ public function testTransactionHasCorrectIsolationLevel() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'isolationLevel' => IsolationLevel::REPEATABLE_READ, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), ]); $reflectedClient = new ReflectionClass($client); @@ -623,7 +623,7 @@ public function testClientPassesReadLockMode() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'readLockMode' => ReadLockMode::PESSIMISTIC, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), ]); $reflectedClient = new ReflectionClass($client); @@ -657,7 +657,7 @@ public function testTransactionHasCorrectReadLockMode() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'readLockMode' => ReadLockMode::PESSIMISTIC, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), ]); $reflectedClient = new ReflectionClass($client); @@ -694,7 +694,7 @@ public function testOptionsWithoutChannelIncreasesChannelId() /** @var SpannerClient $client */ $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -714,7 +714,7 @@ public function testOptionsWithChannelDoesNotIncreasesChannelId() $client = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -731,7 +731,7 @@ public function testOptionsWithChannelDoesNotIncreasesChannelId() $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -761,7 +761,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This client is using a shared channel. This has not been previously used, so this should increase the count. $client = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -777,7 +777,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This client is not using a shared channel, increasing the total once more to 3 channels. $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -792,7 +792,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This is using an entirely new Channel. This should increase the total channels to 4. $client3 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -809,7 +809,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // As this has been seen before, the total should not increase. $client4 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -835,7 +835,7 @@ public function testConfigureKeepAlive() { $client = new SpannerClient([ 'projectId' => 'test-project', - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), ]); $reflection = new ReflectionClass($client); $method = $reflection->getMethod('configureKeepAlive'); @@ -880,7 +880,7 @@ public function testBuiltinMetricsDisabledByDefault() new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'gapicSpannerClient' => $gapicSpannerClient->reveal(), ]); } @@ -895,7 +895,7 @@ public function testBuiltinMetricsCanBeEnabled() new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'credentials' => new InsecureCredentialsWrapper(), 'gapicSpannerClient' => $gapicSpannerClient->reveal(), 'enableBuiltInMetrics' => true, ]); @@ -912,7 +912,7 @@ public function testSpannerClientInstantiatesWithoutDelayWhenMetricsDisabled() $start = microtime(true); new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]); $end = microtime(true); diff --git a/composer.json b/composer.json index 9c3f435b3bc8..94f9079995b1 100644 --- a/composer.json +++ b/composer.json @@ -69,7 +69,6 @@ "grpc/grpc": "^1.13", "google/common-protos": "^4.4", "google/protobuf": "^4.31||^5.34", - "google/grpc-gcp": "^0.4", "ramsey/uuid": "^4.0", "open-telemetry/sdk": "^1.13", "open-telemetry/exporter-otlp": "^1.4" diff --git a/phpcs-ruleset.xml b/phpcs-ruleset.xml index ef321333c1a9..f0f7082bd198 100644 --- a/phpcs-ruleset.xml +++ b/phpcs-ruleset.xml @@ -26,6 +26,7 @@ Bigtable/tests/Conformance/proxy/src Core/src/Testing Gax/src/Testing + Gax/tests/Testing Gax/tests/Unit/GapicClientTraitTest.php GSuiteAddOns/external OsLogin/src/Common From 3971026075cfdf8a2a5190148962af32a869570d Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 28 Sep 2026 20:05:00 +0000 Subject: [PATCH 08/15] docs(gax): add MIGRATING.md for v2 --- Gax/MIGRATING.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Gax/MIGRATING.md diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md new file mode 100644 index 000000000000..ded86d6a9f33 --- /dev/null +++ b/Gax/MIGRATING.md @@ -0,0 +1,57 @@ +# Migrating Google API Core (GAX) from V1 to V2 + +## How to upgrade + +Update your `google/gax` dependency to `^2.0`: + +```json +{ + "require": { + "google/gax": "^2.0" + } +} +``` + +## Breaking Changes + +### Removed Classes, Interfaces, and Traits + +- **`Google\ApiCore\ServiceAddressTrait`**: Replaced by `Google\ApiCore\ApiEndpointTrait` (`self::normalizeServiceAddress()` is now `self::normalizeApiEndpoint()`). +- **`Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface`**: Removed. Extend `Grpc\Interceptor` directly instead. +- **`Google\ApiCore\Testing\MockGrpcTransport`**: Moved to the internal test suite (`Google\ApiCore\Tests\Testing\MockGrpcTransport`) and is no longer distributed with the package. + +### Removed Dependencies + +- **`google/grpc-gcp`**: Removed along with the `gcpApiConfigPath` client option, `ClientOptionsTrait::initGrpcGcpConfig()`, and `Grpc\Gcp\GCPServerStreamCall` handling in `ServerStreamingCallWrapper`. + +### Removed Options and Credential Formats + +- **`serviceAddress` client option**: Removed. Use `apiEndpoint` instead. +- **`gcpApiConfigPath` client option**: Removed along with `google/grpc-gcp`. +- **`operationsClientClass` client option**: Removed. Pass a pre-constructed client via the `operationsClient` option instead. +- **`string|array` (`keyFile`) in `credentials` client option and `CredentialsWrapper::build()`**: + - Passing a file path (`string`) or decoded JSON keyfile (`array`) directly to the `credentials` option in `ClientOptions` / `ClientOptionsTrait`, or passing `keyFile` to `CredentialsWrapper::build()`, has been removed. + - Pass an instance of `Google\Auth\FetchAuthTokenInterface` or `Google\ApiCore\HeaderCredentialsInterface` to `credentials` (or use `credentialsConfig['keyFile']` when configuring client options). +- **`CallOptions::setTransportSpecificOptions()`**: Removed. Use `CallOptions::setTransportOptions()` instead. + +### Removed Methods and Legacy V1 Client Surface Support + +- **`CredentialsWrapper::getBearerString()`**: Removed. Use `CredentialsWrapper::getAuthorizationHeaderCallback()` instead. +- **`ClientOptionsTrait::modifyClientOptions(array &$options)`**: Removed. Clients using `GapicClientTrait` can override `preBuildClientOptions(array $options): array` instead. +- **`ClientOptionsTrait::initGrpcGcpConfig()`**: Removed. +- **V1 GAPIC surface backwards-compatibility mode**: + - Removed `GapicClientTrait::$backwardsCompatibilityMode` and `GapicClientTrait::isBackwardsCompatibilityMode()`. + - Removed the `User-Agent: gcloud-php-legacy/*` and `gcloud-php-new/*` headers previously added in `GapicClientTrait`. + - Default long-running operations client in `GapicClientTrait` and `OperationResponse` now uses the V2 surface `Google\LongRunning\Client\OperationsClient` instead of `Google\LongRunning\OperationsClient`, and `OperationResponse` requires operation request classes implementing `::build()`. + +### Credentials Hierarchy Changes + +- **`Google\ApiCore\InsecureCredentialsWrapper`** now implements `Google\ApiCore\HeaderCredentialsInterface` directly and no longer extends `Google\ApiCore\CredentialsWrapper`. +- **`Google\ApiCore\HeaderCredentialsInterface`** now extends `Google\Auth\GetQuotaProjectInterface`. +- **`GapicClientTrait::getCredentialsWrapper()`** now returns `HeaderCredentialsInterface` instead of `CredentialsWrapper`. +- **`ResumableUploadClient::__construct()`** now accepts `HeaderCredentialsInterface` instead of `CredentialsWrapper`. + +### Strict Types and Method Signatures + +- Added `declare(strict_types=1)` across all `Google\ApiCore` files. +- Added native parameter, property, and return type declarations across `AgentHeader`, `ApiEndpointTrait`, `ArrayTrait`, `BidiStream`, `Call`, `ClientOptionsTrait`, `ClientStream`, `CredentialsWrapper`, `FixedSizeCollection`, `GapicClientTrait`, `KnownTypes`, `OperationResponse`, `Page`, `PagedListResponse`, `PollingTrait`, `ResourceHelperTrait`, `RetrySettings`, `ServerStream`, `ValidationTrait`, and `Version`. From 274772e93a9c76b5fa8c761c57449768769880f2 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 28 Sep 2026 23:58:48 +0000 Subject: [PATCH 09/15] fix(gax): fix PagedListResponse::getIterator return type, unused import, and docfx fixture --- Gax/src/Options/ClientOptions.php | 1 - Gax/src/PagedListResponse.php | 3 +- dev/tests/fixtures/phpdoc/gax.xml | 120 ------------------------------ 3 files changed, 2 insertions(+), 122 deletions(-) diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 825e2c54f7b1..52fde667bf79 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -39,7 +39,6 @@ use Google\ApiCore\HeaderCredentialsInterface; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; -use InvalidArgumentException; use Psr\Log\LoggerInterface; /** diff --git a/Gax/src/PagedListResponse.php b/Gax/src/PagedListResponse.php index ddc60d7353ea..c63a9758329d 100644 --- a/Gax/src/PagedListResponse.php +++ b/Gax/src/PagedListResponse.php @@ -35,6 +35,7 @@ use Generator; use IteratorAggregate; +use Traversable; /** * Response object for paged results from a list API method @@ -123,7 +124,7 @@ public function iterateAllElements(): Generator * @return Generator * @throws ValidationException */ - public function getIterator(): Generator + public function getIterator(): Traversable { foreach ($this->iteratePages() as $page) { foreach ($page as $key => $element) { diff --git a/dev/tests/fixtures/phpdoc/gax.xml b/dev/tests/fixtures/phpdoc/gax.xml index 860903a5945d..6091c5b8c57d 100644 --- a/dev/tests/fixtures/phpdoc/gax.xml +++ b/dev/tests/fixtures/phpdoc/gax.xml @@ -23076,126 +23076,6 @@ make to a mock gRPC stub. - - - - - - - - - - - - - - - - - - UnaryInterceptorInterface - \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface - - Temporary class to support an interceptor-like interface until gRPC interceptor support is -available. - - - - - - - - interceptUnaryUnary - \Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface::interceptUnaryUnary() - - - method - - string - - - - argument - - \Google\Protobuf\Internal\Message - - - - deserialize - - callable - - - - metadata - - array - - - - options - - array - - - - continuation - - callable - - - - - - - - - - - - - - - - - - - - - From 1bb7d91123e10c1b56d041997e3f380e7dd62fe5 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Tue, 29 Sep 2026 19:04:51 +0000 Subject: [PATCH 10/15] feat(Gax): preserve client options and add strict types across remaining GAX classes --- Gax/MIGRATING.md | 12 ++- Gax/src/ApiException.php | 52 ++++++------- Gax/src/ClientOptionsTrait.php | 32 +++++++- Gax/src/CredentialsWrapper.php | 50 ++++++++++--- Gax/src/GPBLabel.php | 45 ------------ Gax/src/GPBType.php | 60 --------------- Gax/src/GapicClientTrait.php | 25 +++++-- Gax/src/InsecureRequestBuilder.php | 2 +- .../CredentialsWrapperMiddleware.php | 14 ++-- Gax/src/Middleware/FixedHeaderMiddleware.php | 10 ++- Gax/src/Middleware/MiddlewareInterface.php | 30 +++++--- Gax/src/Middleware/OperationsMiddleware.php | 5 +- .../Middleware/OptionsFilterMiddleware.php | 10 ++- Gax/src/Middleware/PagedMiddleware.php | 3 +- .../RequestAutoPopulationMiddleware.php | 15 ++-- .../Middleware/ResponseMetadataMiddleware.php | 2 +- Gax/src/Middleware/RetryMiddleware.php | 28 ++++--- .../Middleware/TransportCallMiddleware.php | 10 ++- Gax/src/Options/ClientOptions.php | 23 ++++-- Gax/src/PageStreamingDescriptor.php | 32 ++++---- Gax/src/PathTemplate.php | 12 +-- Gax/src/RequestBuilder.php | 18 ++--- Gax/src/RequestParamsHeaderDescriptor.php | 7 +- .../AbsoluteResourceTemplate.php | 17 ++--- Gax/src/ResourceTemplate/Parser.php | 14 ++-- .../RelativeResourceTemplate.php | 22 +++--- .../ResourceTemplateInterface.php | 9 ++- Gax/src/ResourceTemplate/Segment.php | 18 ++--- .../ResumableUpload/ResumableUploadClient.php | 2 +- .../ResumableUploadTransportInterface.php | 2 +- Gax/src/Serializer.php | 73 ++++++++++--------- Gax/src/ServerStreamingCallInterface.php | 26 ++++--- Gax/src/Testing/MockBidiStreamingCall.php | 22 +++--- Gax/src/Testing/MockClientStreamingCall.php | 16 ++-- Gax/src/Testing/MockServerStreamingCall.php | 41 +++++++++-- Gax/src/Testing/MockStatus.php | 8 +- Gax/src/Testing/MockStubTrait.php | 55 ++++++++------ Gax/src/Testing/MockTransport.php | 17 +++-- Gax/src/Testing/MockUnaryCall.php | 10 +-- Gax/src/Testing/ReceivedRequest.php | 21 ++++-- Gax/src/Testing/SerializationTrait.php | 5 +- Gax/src/Transport/Grpc/ForwardingCall.php | 12 +-- .../Grpc/ForwardingServerStreamingCall.php | 7 +- .../Transport/Grpc/ForwardingUnaryCall.php | 4 +- .../Grpc/ServerStreamingCallWrapper.php | 18 +++-- Gax/src/Transport/GrpcFallbackTransport.php | 23 ++++-- Gax/src/Transport/GrpcTransport.php | 27 ++++--- Gax/src/Transport/HttpUnaryTransportTrait.php | 32 +++----- Gax/src/Transport/Rest/JsonStreamDecoder.php | 11 +-- .../Rest/RestServerStreamingCall.php | 25 ++++--- Gax/src/Transport/RestTransport.php | 33 ++++----- Gax/src/Transport/TransportInterface.php | 10 +-- Gax/tests/Unit/ClientOptionsTraitTest.php | 27 +++++++ Gax/tests/Unit/CredentialsWrapperTest.php | 73 +++++++++++++++++++ Gax/tests/Unit/GapicClientTraitTest.php | 46 ++++++++++-- .../Middleware/FixedHeaderMiddlewareTest.php | 4 + .../RequestAutoPopulationMiddlewareTest.php | 10 ++- Gax/tests/Unit/PathTemplateTest.php | 8 -- .../ResumableUploadClientTest.php | 8 +- .../ResumableUpload/ResumableUploadTest.php | 8 +- Logging/tests/Unit/Connection/GapicTest.php | 2 +- PubSub/tests/Unit/BatchPublisherTest.php | 6 +- PubSub/tests/Unit/PubSubClientTest.php | 4 +- .../Middleware/MetricsAttemptMiddleware.php | 8 +- .../Middleware/MetricsOperationMiddleware.php | 8 +- .../Middleware/RequestIdHeaderMiddleware.php | 10 ++- Spanner/src/SpannerClient.php | 4 +- .../Unit/RequestIdHeaderMiddlewareTest.php | 8 +- Spanner/tests/Unit/SpannerClientTest.php | 34 ++++----- 69 files changed, 792 insertions(+), 553 deletions(-) delete mode 100644 Gax/src/GPBLabel.php delete mode 100644 Gax/src/GPBType.php diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index ded86d6a9f33..e5b583b6920c 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -16,6 +16,7 @@ Update your `google/gax` dependency to `^2.0`: ### Removed Classes, Interfaces, and Traits +- **`Google\ApiCore\GPBType` and `Google\ApiCore\GPBLabel`**: Removed. Use `Google\Protobuf\Internal\GPBType` and `Google\Protobuf\Internal\GPBLabel` instead. - **`Google\ApiCore\ServiceAddressTrait`**: Replaced by `Google\ApiCore\ApiEndpointTrait` (`self::normalizeServiceAddress()` is now `self::normalizeApiEndpoint()`). - **`Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface`**: Removed. Extend `Grpc\Interceptor` directly instead. - **`Google\ApiCore\Testing\MockGrpcTransport`**: Moved to the internal test suite (`Google\ApiCore\Tests\Testing\MockGrpcTransport`) and is no longer distributed with the package. @@ -24,21 +25,17 @@ Update your `google/gax` dependency to `^2.0`: - **`google/grpc-gcp`**: Removed along with the `gcpApiConfigPath` client option, `ClientOptionsTrait::initGrpcGcpConfig()`, and `Grpc\Gcp\GCPServerStreamCall` handling in `ServerStreamingCallWrapper`. -### Removed Options and Credential Formats +### Removed Options -- **`serviceAddress` client option**: Removed. Use `apiEndpoint` instead. - **`gcpApiConfigPath` client option**: Removed along with `google/grpc-gcp`. - **`operationsClientClass` client option**: Removed. Pass a pre-constructed client via the `operationsClient` option instead. -- **`string|array` (`keyFile`) in `credentials` client option and `CredentialsWrapper::build()`**: - - Passing a file path (`string`) or decoded JSON keyfile (`array`) directly to the `credentials` option in `ClientOptions` / `ClientOptionsTrait`, or passing `keyFile` to `CredentialsWrapper::build()`, has been removed. - - Pass an instance of `Google\Auth\FetchAuthTokenInterface` or `Google\ApiCore\HeaderCredentialsInterface` to `credentials` (or use `credentialsConfig['keyFile']` when configuring client options). - **`CallOptions::setTransportSpecificOptions()`**: Removed. Use `CallOptions::setTransportOptions()` instead. ### Removed Methods and Legacy V1 Client Surface Support - **`CredentialsWrapper::getBearerString()`**: Removed. Use `CredentialsWrapper::getAuthorizationHeaderCallback()` instead. -- **`ClientOptionsTrait::modifyClientOptions(array &$options)`**: Removed. Clients using `GapicClientTrait` can override `preBuildClientOptions(array $options): array` instead. - **`ClientOptionsTrait::initGrpcGcpConfig()`**: Removed. +- **`HttpUnaryTransportTrait::startServerStreamingCall()`**: Removed (along with the `unsupportedServerStreamingCall` trait alias on `RestTransport`). - **V1 GAPIC surface backwards-compatibility mode**: - Removed `GapicClientTrait::$backwardsCompatibilityMode` and `GapicClientTrait::isBackwardsCompatibilityMode()`. - Removed the `User-Agent: gcloud-php-legacy/*` and `gcloud-php-new/*` headers previously added in `GapicClientTrait`. @@ -54,4 +51,5 @@ Update your `google/gax` dependency to `^2.0`: ### Strict Types and Method Signatures - Added `declare(strict_types=1)` across all `Google\ApiCore` files. -- Added native parameter, property, and return type declarations across `AgentHeader`, `ApiEndpointTrait`, `ArrayTrait`, `BidiStream`, `Call`, `ClientOptionsTrait`, `ClientStream`, `CredentialsWrapper`, `FixedSizeCollection`, `GapicClientTrait`, `KnownTypes`, `OperationResponse`, `Page`, `PagedListResponse`, `PollingTrait`, `ResourceHelperTrait`, `RetrySettings`, `ServerStream`, `ValidationTrait`, and `Version`. +- Added native parameter, property, and return type declarations across all `Google\ApiCore` classes, interfaces (`TransportInterface`, `MiddlewareInterface`, `ResourceTemplateInterface`, `ServerStreamingCallInterface`, `ResumableUploadTransportInterface`, `HeaderCredentialsInterface`), and traits. +- **`PathTemplate::__construct(string $path)`** now requires a non-null `string`. diff --git a/Gax/src/ApiException.php b/Gax/src/ApiException.php index e3360138b38d..dfc881dfe5b6 100644 --- a/Gax/src/ApiException.php +++ b/Gax/src/ApiException.php @@ -44,10 +44,10 @@ */ class ApiException extends Exception { - private $status; - private $metadata; - private $basicMessage; - private $decodedMetadataErrorInfo; + private ?string $status; + private mixed $metadata; + private ?string $basicMessage; + private ?array $decodedMetadataErrorInfo = null; private array $protobufErrors; /** @@ -83,7 +83,7 @@ public function __construct( $this->protobufErrors = $protobufErrors; } - public function getStatus() + public function getStatus(): ?string { return $this->status; } @@ -98,7 +98,7 @@ public function getStatus() * @type array|null $errorInfoMetadata * } */ - private static function decodeMetadataErrorInfo(array $metadata) + private static function decodeMetadataErrorInfo(array $metadata): array { $details = []; // ApiExceptions created from RPC status have metadata that is an array of objects. @@ -119,7 +119,7 @@ private static function decodeMetadataErrorInfo(array $metadata) * Returns the `reason` in ErrorInfo for an exception, or null if there is no ErrorInfo. * @return string|null $reason */ - public function getReason() + public function getReason(): ?string { return ($this->decodedMetadataErrorInfo) ? $this->decodedMetadataErrorInfo['reason'] : null; } @@ -128,7 +128,7 @@ public function getReason() * Returns the `domain` in ErrorInfo for an exception, or null if there is no ErrorInfo. * @return string|null $domain */ - public function getDomain() + public function getDomain(): ?string { return ($this->decodedMetadataErrorInfo) ? $this->decodedMetadataErrorInfo['domain'] : null; } @@ -137,7 +137,7 @@ public function getDomain() * Returns the `metadata` in ErrorInfo for an exception, or null if there is no ErrorInfo. * @return array|null $errorInfoMetadata */ - public function getErrorInfoMetadata() + public function getErrorInfoMetadata(): ?array { return ($this->decodedMetadataErrorInfo) ? $this->decodedMetadataErrorInfo['errorInfoMetadata'] : null; } @@ -155,7 +155,7 @@ public function getErrorDetails(): array * @param stdClass $status * @return ApiException */ - public static function createFromStdClass(stdClass $status) + public static function createFromStdClass(stdClass $status): self { $metadata = property_exists($status, 'metadata') ? $status->metadata : null; $errors = []; @@ -173,15 +173,15 @@ public static function createFromStdClass(stdClass $status) * @param string $basicMessage * @param int $rpcCode * @param array|null $metadata - * @param Exception $previous + * @param Exception|null $previous * @return ApiException */ public static function createFromApiResponse( - $basicMessage, - $rpcCode, + string $basicMessage, + int $rpcCode, ?array $metadata = null, ?Exception $previous = null - ) { + ): self { $errors = []; return self::create( $basicMessage, @@ -199,15 +199,15 @@ public static function createFromApiResponse( * @param string $basicMessage * @param int $rpcCode * @param array|null $metadata - * @param Exception $previous + * @param Exception|null $previous * @return ApiException */ public static function createFromRestApiResponse( - $basicMessage, - $rpcCode, + string $basicMessage, + int $rpcCode, ?array $metadata = null, ?Exception $previous = null - ) { + ): self { return self::create( $basicMessage, $rpcCode, @@ -228,7 +228,7 @@ public static function createFromRestApiResponse( * @type array $errorInfoMetadata * } */ - private static function containsErrorInfo(array $decodedMetadata) + private static function containsErrorInfo(array $decodedMetadata): array { if (empty($decodedMetadata)) { return []; @@ -262,11 +262,11 @@ private static function containsErrorInfo(array $decodedMetadata) private static function create( string $basicMessage, int $rpcCode, - $metadata, + mixed $metadata, array $decodedMetadata, ?array $protobufErrors = null, ?Exception $previous = null - ) { + ): self { $containsErrorInfo = self::containsErrorInfo($decodedMetadata); $rpcStatus = ApiStatus::statusFromRpcCode($rpcCode); $messageData = [ @@ -336,7 +336,7 @@ private static function decodeMetadataToProtobufErrors(array $metadata): array * @param Status $status * @return ApiException */ - public static function createFromRpcStatus(Status $status) + public static function createFromRpcStatus(Status $status): self { return self::create( $status->getMessage(), @@ -356,7 +356,7 @@ public static function createFromRpcStatus(Status $status) * @return ApiException * @throws ValidationException */ - public static function createFromRequestException(RequestException $ex, bool $isStream = false) + public static function createFromRequestException(RequestException $ex, bool $isStream = false): self { // Guzzle 7 carries the response on RequestException, Guzzle 8 only on // its ResponseException subclass, hence the method_exists() check. @@ -387,15 +387,15 @@ public static function createFromRequestException(RequestException $ex, bool $is /** * @return null|string */ - public function getBasicMessage() + public function getBasicMessage(): ?string { return $this->basicMessage; } /** - * @return mixed[] + * @return mixed[]|null */ - public function getMetadata() + public function getMetadata(): mixed { return $this->metadata; } diff --git a/Gax/src/ClientOptionsTrait.php b/Gax/src/ClientOptionsTrait.php index b4c5eb4921ee..af368900c690 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -175,6 +175,18 @@ private function buildClientOptions(array|ClientOptions $options): array $options['transportConfig']['grpc-fallback']['logger'] = $options['logger'] ?? null; } + $preModifiedOptions = $options; + $this->modifyClientOptions($options); + // NOTE: this is required to ensure backwards compatiblity with $options['apiEndpoint'] + if ($options['apiEndpoint'] !== $preModifiedOptions['apiEndpoint']) { + $apiEndpoint = $options['apiEndpoint']; + } + + // serviceAddress is now deprecated and acts as an alias for apiEndpoint + if (isset($options['serviceAddress'])) { + $apiEndpoint = $this->pluck('serviceAddress', $options, false); + } + // If an API endpoint is different form the default, ensure the "audience" does not conflict // with the custom endpoint by setting "user defined" scopes. if ($apiEndpoint @@ -252,14 +264,14 @@ private static function determineMtlsEndpoint(string $apiEndpoint): string } /** - * @param FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials + * @param string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * @param array $credentialsConfig * @param string $universeDomain * @return HeaderCredentialsInterface * @throws ValidationException */ private function createCredentialsWrapper( - FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, array $credentialsConfig, string $universeDomain ): HeaderCredentialsInterface { @@ -267,6 +279,10 @@ private function createCredentialsWrapper( return CredentialsWrapper::build($credentialsConfig, $universeDomain); } + if (is_string($credentials) || is_array($credentials)) { + return CredentialsWrapper::build(['keyFile' => $credentials] + $credentialsConfig, $universeDomain); + } + if ($credentials instanceof FetchAuthTokenInterface) { $authHttpHandler = $credentialsConfig['authHttpHandler'] ?? null; return new CredentialsWrapper($credentials, $authHttpHandler, $universeDomain); @@ -289,6 +305,18 @@ private static function supportedTransports(): array // functionality. These extension points are currently considered // private and may change at any time. + /** + * Modify options passed to the client before calling setClientOptions. + * + * @param array $options + * @access private + * @internal + */ + protected function modifyClientOptions(array &$options) + { + // Do nothing - this method exists to allow option modification by partial veneers. + } + /** * @param null|false|LoggerInterface $logger * @param string $options diff --git a/Gax/src/CredentialsWrapper.php b/Gax/src/CredentialsWrapper.php index f4a393e942ff..20517a017971 100644 --- a/Gax/src/CredentialsWrapper.php +++ b/Gax/src/CredentialsWrapper.php @@ -39,6 +39,7 @@ use Google\Auth\Cache\MemoryCacheItemPool; use Google\Auth\Credentials\GCECredentials; use Google\Auth\Credentials\ServiceAccountCredentials; +use Google\Auth\CredentialsLoader; use Google\Auth\FetchAuthTokenCache; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetQuotaProjectInterface; @@ -91,6 +92,10 @@ public function __construct( * @param array $args { * An array of optional arguments. * + * @type string|array $keyFile + * Credentials to be used. Accepts either a path to a credentials file, or a decoded + * credentials file as a PHP array. If this is not specified, application default + * credentials will be used. * @type string[] $scopes * A string array of scopes to use when acquiring credentials. * @type callable $authHttpHandler @@ -125,6 +130,7 @@ public static function build( string $universeDomain = GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN ): self { $args += [ + 'keyFile' => null, 'scopes' => null, 'authHttpHandler' => null, 'enableCaching' => true, @@ -136,17 +142,39 @@ public static function build( 'enableRegionalAccessBoundary' => false, ]; - $loader = self::buildApplicationDefaultCredentials( - $args['scopes'], - $args['authHttpHandler'], - $args['authCacheOptions'], - $args['authCache'], - $args['quotaProject'], - $args['defaultScopes'], - $args['enableRegionalAccessBoundary'], - ); - if ($loader instanceof FetchAuthTokenCache) { - $loader = $loader->getFetcher(); + $keyFile = $args['keyFile']; + + if (is_null($keyFile)) { + $loader = self::buildApplicationDefaultCredentials( + $args['scopes'], + $args['authHttpHandler'], + $args['authCacheOptions'], + $args['authCache'], + $args['quotaProject'], + $args['defaultScopes'], + $args['enableRegionalAccessBoundary'], + ); + if ($loader instanceof FetchAuthTokenCache) { + $loader = $loader->getFetcher(); + } + } else { + if (is_string($keyFile)) { + if (!file_exists($keyFile)) { + throw new ValidationException("Could not find keyfile: $keyFile"); + } + $keyFile = json_decode(file_get_contents($keyFile), true); + } + + if (isset($args['quotaProject'])) { + $keyFile['quota_project_id'] = $args['quotaProject']; + } + + $loader = CredentialsLoader::makeCredentials( + $args['scopes'], + $keyFile, + $args['defaultScopes'], + $args['enableRegionalAccessBoundary'], + ); } if ($loader instanceof ServiceAccountCredentials && $args['useJwtAccessWithScope']) { diff --git a/Gax/src/GPBLabel.php b/Gax/src/GPBLabel.php deleted file mode 100644 index 23ae4ed3e068..000000000000 --- a/Gax/src/GPBLabel.php +++ /dev/null @@ -1,45 +0,0 @@ -handler)($call, $options); * // modify the response (post-request) @@ -139,7 +142,10 @@ public function addMiddleware(callable $middlewareCallable): void * public function __construct(private MiddlewareInterface $handler) { * } * - * public function __invoke(Call $call, array $options) { + * public function __invoke( + * Call $call, + * array $options + * ): PromiseInterface|ClientStream|ServerStream|BidiStream { * // modify call and options (pre-request) * $response = ($this->handler)($call, $options); * // modify the response (post-request) @@ -221,11 +227,14 @@ protected function getCredentialsWrapper(): ?HeaderCredentialsInterface * path to a JSON file, or a PHP array containing the decoded JSON data. * By default this settings points to the default client config file, which is provided * in the resources folder. - * @type FetchAuthTokenInterface|HeaderCredentialsInterface $credentials + * @type string|array|FetchAuthTokenInterface|HeaderCredentialsInterface $credentials * The credentials to be used by the client to authorize API calls. This option - * accepts a pre-constructed \Google\Auth\FetchAuthTokenInterface object or - * \Google\ApiCore\HeaderCredentialsInterface object. Note that when one of these - * objects are provided, any settings in $authConfig will be ignored. + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * \Google\Auth\FetchAuthTokenInterface object or \Google\ApiCore\HeaderCredentialsInterface + * object. Note that when one of these objects are provided, any settings in + * $authConfig will be ignored. * @type array $credentialsConfig * Options used to configure credentials, including auth token caching, for the client. * For a full list of supporting configuration options, see @@ -266,6 +275,10 @@ protected function getCredentialsWrapper(): ?HeaderCredentialsInterface */ private function setClientOptions(array $options): void { + // serviceAddress is now deprecated and acts as an alias for apiEndpoint + if (isset($options['serviceAddress'])) { + $options['apiEndpoint'] = $this->pluck('serviceAddress', $options, false); + } self::validateNotNull($options, [ 'apiEndpoint', 'serviceName', diff --git a/Gax/src/InsecureRequestBuilder.php b/Gax/src/InsecureRequestBuilder.php index 914570248cc7..e8b065565824 100644 --- a/Gax/src/InsecureRequestBuilder.php +++ b/Gax/src/InsecureRequestBuilder.php @@ -16,7 +16,7 @@ class InsecureRequestBuilder extends RequestBuilder * @param array $queryParams * @return UriInterface */ - protected function buildUri(string $path, array $queryParams) + protected function buildUri(string $path, array $queryParams): UriInterface { $uri = Utils::uriFor(sprintf( 'http://%s%s', diff --git a/Gax/src/Middleware/CredentialsWrapperMiddleware.php b/Gax/src/Middleware/CredentialsWrapperMiddleware.php index e406e77662a9..b6e1ffb4aa34 100644 --- a/Gax/src/Middleware/CredentialsWrapperMiddleware.php +++ b/Gax/src/Middleware/CredentialsWrapperMiddleware.php @@ -33,9 +33,12 @@ */ namespace Google\ApiCore\Middleware; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; -use Google\ApiCore\CredentialsWrapper; +use Google\ApiCore\ClientStream; use Google\ApiCore\HeaderCredentialsInterface; +use Google\ApiCore\ServerStream; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware which adds a CredentialsWrapper object to the call options. @@ -47,8 +50,7 @@ class CredentialsWrapperMiddleware implements MiddlewareInterface /** @var callable */ private $nextHandler; - /** @var HeaderCredentialsInterface */ - private HeaderCredentialsInterface $credentialsWrapper; + private HeaderCredentialsInterface $credentialsWrapper; public function __construct( callable $nextHandler, @@ -58,8 +60,10 @@ public function __construct( $this->credentialsWrapper = $credentialsWrapper; } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $next = $this->nextHandler; return $next( $call, diff --git a/Gax/src/Middleware/FixedHeaderMiddleware.php b/Gax/src/Middleware/FixedHeaderMiddleware.php index 89eb1c782354..1c0e2469dda5 100644 --- a/Gax/src/Middleware/FixedHeaderMiddleware.php +++ b/Gax/src/Middleware/FixedHeaderMiddleware.php @@ -34,7 +34,11 @@ namespace Google\ApiCore\Middleware; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; +use Google\ApiCore\ServerStream; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware to add fixed headers to an API call. @@ -58,8 +62,10 @@ public function __construct( $this->overrideUserHeaders = $overrideUserHeaders; } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $userHeaders = $options['headers'] ?? []; if ($this->overrideUserHeaders) { $options['headers'] = $this->headers + $userHeaders; diff --git a/Gax/src/Middleware/MiddlewareInterface.php b/Gax/src/Middleware/MiddlewareInterface.php index c197d771cb46..004cce465f98 100644 --- a/Gax/src/Middleware/MiddlewareInterface.php +++ b/Gax/src/Middleware/MiddlewareInterface.php @@ -50,20 +50,27 @@ * pass the handler in through the constructor: * * ``` + * use Google\ApiCore\BidiStream; * use Google\ApiCore\Call; + * use Google\ApiCore\ClientStream; * use Google\ApiCore\Middleware\MiddlewareInterface; + * use Google\ApiCore\ServerStream; + * use GuzzleHttp\Promise\PromiseInterface; * * class MyTestMiddleware implements MiddlewareInterface * { - * public function __construct(MiddlewareInterface $handler) - * { - *. $this->handler = $handler; - * } - * public function __invoke(Call $call, array $options) - * { - * echo "Logging info about the call: " . $call->getMethod(); - * return ($this->handler)($call, $options); - * } + * public function __construct( + * private MiddlewareInterface $handler + * ) { + * } + * + * public function __invoke( + * Call $call, + * array $options + * ): PromiseInterface|ClientStream|ServerStream|BidiStream { + * echo "Logging info about the call: " . $call->getMethod(); + * return ($this->handler)($call, $options); + * } * } * ``` * @@ -90,5 +97,8 @@ interface MiddlewareInterface * @param array $options * @return PromiseInterface|ClientStream|ServerStream|BidiStream */ - public function __invoke(Call $call, array $options); + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream; } diff --git a/Gax/src/Middleware/OperationsMiddleware.php b/Gax/src/Middleware/OperationsMiddleware.php index bfbb691a764d..07bbe42cc23c 100644 --- a/Gax/src/Middleware/OperationsMiddleware.php +++ b/Gax/src/Middleware/OperationsMiddleware.php @@ -36,6 +36,7 @@ use Google\ApiCore\Call; use Google\ApiCore\OperationResponse; use Google\Protobuf\Internal\Message; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware which wraps the response in an OperationResponse object. @@ -51,7 +52,7 @@ class OperationsMiddleware implements MiddlewareInterface public function __construct( callable $nextHandler, - $operationsClient, + object $operationsClient, array $descriptor ) { $this->nextHandler = $nextHandler; @@ -59,7 +60,7 @@ public function __construct( $this->descriptor = $descriptor; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $next = $this->nextHandler; return $next( diff --git a/Gax/src/Middleware/OptionsFilterMiddleware.php b/Gax/src/Middleware/OptionsFilterMiddleware.php index 7359c692e89e..23fe9bf8b655 100644 --- a/Gax/src/Middleware/OptionsFilterMiddleware.php +++ b/Gax/src/Middleware/OptionsFilterMiddleware.php @@ -34,7 +34,11 @@ namespace Google\ApiCore\Middleware; use Google\ApiCore\ArrayTrait; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; +use Google\ApiCore\ServerStream; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware which filters the $options array. @@ -57,8 +61,10 @@ public function __construct( $this->permittedOptions = $permittedOptions; } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $next = $this->nextHandler; $filteredOptions = $this->pluckArray($this->permittedOptions, $options); return $next( diff --git a/Gax/src/Middleware/PagedMiddleware.php b/Gax/src/Middleware/PagedMiddleware.php index 9162a505fabc..8ea8c70b88a1 100644 --- a/Gax/src/Middleware/PagedMiddleware.php +++ b/Gax/src/Middleware/PagedMiddleware.php @@ -38,6 +38,7 @@ use Google\ApiCore\PagedListResponse; use Google\ApiCore\PageStreamingDescriptor; use Google\Protobuf\Internal\Message; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware which wraps the response in an PagedListResponses object. @@ -62,7 +63,7 @@ public function __construct( $this->descriptor = $descriptor; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $next = $this->nextHandler; $descriptor = $this->descriptor; diff --git a/Gax/src/Middleware/RequestAutoPopulationMiddleware.php b/Gax/src/Middleware/RequestAutoPopulationMiddleware.php index 36a9386edbe2..fb1cbb98be5e 100644 --- a/Gax/src/Middleware/RequestAutoPopulationMiddleware.php +++ b/Gax/src/Middleware/RequestAutoPopulationMiddleware.php @@ -34,7 +34,10 @@ namespace Google\ApiCore\Middleware; use Google\Api\FieldInfo\Format; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; +use Google\ApiCore\ServerStream; use GuzzleHttp\Promise\PromiseInterface; use Ramsey\Uuid\Uuid; @@ -50,8 +53,8 @@ class RequestAutoPopulationMiddleware implements MiddlewareInterface /** @var callable */ private $nextHandler; - /** @var array */ - private $autoPopulationSettings; + /** @var array */ + private array $autoPopulationSettings; public function __construct( callable $nextHandler, @@ -65,10 +68,12 @@ public function __construct( * @param Call $call * @param array $options * - * @return PromiseInterface + * @return PromiseInterface|ClientStream|ServerStream|BidiStream */ - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $next = $this->nextHandler; if (empty($this->autoPopulationSettings)) { diff --git a/Gax/src/Middleware/ResponseMetadataMiddleware.php b/Gax/src/Middleware/ResponseMetadataMiddleware.php index 31bb8454ee1b..14867233dd11 100644 --- a/Gax/src/Middleware/ResponseMetadataMiddleware.php +++ b/Gax/src/Middleware/ResponseMetadataMiddleware.php @@ -55,7 +55,7 @@ public function __construct(callable $nextHandler) $this->nextHandler = $nextHandler; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $metadataReceiver = new Promise(); $options['metadataCallback'] = function ($metadata) use ($metadataReceiver) { diff --git a/Gax/src/Middleware/RetryMiddleware.php b/Gax/src/Middleware/RetryMiddleware.php index c1d138edd3ee..db7c01615df7 100644 --- a/Gax/src/Middleware/RetryMiddleware.php +++ b/Gax/src/Middleware/RetryMiddleware.php @@ -35,8 +35,11 @@ use Google\ApiCore\ApiException; use Google\ApiCore\ApiStatus; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; use Google\ApiCore\RetrySettings; +use Google\ApiCore\ServerStream; use GuzzleHttp\Promise\PromiseInterface; /** @@ -62,8 +65,8 @@ class RetryMiddleware implements MiddlewareInterface public function __construct( callable $nextHandler, RetrySettings $retrySettings, - $deadlineMs = null, - $retryAttempts = 0, + ?float $deadlineMs = null, + int $retryAttempts = 0, ?callable $delayHandler = null ) { $this->nextHandler = $nextHandler; @@ -77,10 +80,12 @@ public function __construct( * @param Call $call * @param array $options * - * @return PromiseInterface + * @return PromiseInterface|ClientStream|ServerStream|BidiStream */ - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $nextHandler = $this->nextHandler; if (!isset($options['timeoutMillis'])) { @@ -134,11 +139,14 @@ public function __invoke(Call $call, array $options) * @param array $options * @param string $status * - * @return PromiseInterface + * @return PromiseInterface|ClientStream|ServerStream|BidiStream * @throws ApiException */ - private function retry(Call $call, array $options, string $status) - { + private function retry( + Call $call, + array $options, + string $status + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $delayMult = $this->retrySettings->getRetryDelayMultiplier(); $maxDelayMs = $this->retrySettings->getMaxRetryDelayMillis(); $timeoutMult = $this->retrySettings->getRpcTimeoutMultiplier(); @@ -193,7 +201,7 @@ protected function getCurrentTimeMs(): float /** * This is the default retry behaviour. */ - private function getRetryFunction() + private function getRetryFunction(): callable { return $this->retrySettings->getRetryFunction() ?? function (\Throwable $e, array $options): bool { @@ -215,7 +223,7 @@ function (\Throwable $e, array $options): bool { /** * @param int $millis */ - private function sleepMillis(int $millis) + private function sleepMillis(int $millis): void { usleep($millis * 1000); } diff --git a/Gax/src/Middleware/TransportCallMiddleware.php b/Gax/src/Middleware/TransportCallMiddleware.php index dfd68cc121db..5adddd1776fe 100644 --- a/Gax/src/Middleware/TransportCallMiddleware.php +++ b/Gax/src/Middleware/TransportCallMiddleware.php @@ -33,8 +33,12 @@ */ namespace Google\ApiCore\Middleware; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; +use Google\ApiCore\ServerStream; use Google\ApiCore\Transport\TransportInterface; +use GuzzleHttp\Promise\PromiseInterface; /** * A Middleware in charge of handling the end of the callstack to call the transport layer. @@ -54,8 +58,10 @@ public function __construct( ) { } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $startCallMethod = $this->transportCallMethods[$call->getCallType()]; return $this->transport->$startCallMethod($call, $options); } diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 52fde667bf79..66ea4affe48a 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -70,7 +70,7 @@ class ClientOptions implements ArrayAccess, OptionsInterface private array $clientConfig; - private FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials; + private string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials; private array $credentialsConfig; @@ -111,10 +111,22 @@ class ClientOptions implements ArrayAccess, OptionsInterface * path to a JSON file, or a PHP array containing the decoded JSON data. * By default this settings points to the default client config file, which is provided * in the resources folder. - * @type FetchAuthTokenInterface|HeaderCredentialsInterface $credentials + * @type string|array|FetchAuthTokenInterface|HeaderCredentialsInterface $credentials * This option should only be used with a pre-constructed \Google\Auth\FetchAuthTokenInterface * object or \Google\ApiCore\HeaderCredentialsInterface object. Note that when one of these objects * are provided, any settings in $authConfig will be ignored. + * **Important**: If you are providing a path to a credentials file, or a decoded credentials + * file as a PHP array, this usage is now DEPRECATED. Providing an unvalidated credential + * configuration to Google APIs can compromise the security of your systems and data. It is now + * recommended to create the credentials explicitly: + * ``` + * use Google\Auth\Credentials\ServiceAccountCredentials; + * use Google\ApiCore\Options\ClientOptions; + * $creds = new ServiceAccountCredentials($scopes, $json); + * $options = new ClientOptions(['credentials' => $creds]); + * ``` + * For more information + * {@see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials} * @type array $credentialsConfig * Options used to configure credentials, including auth token caching, for the client. * For a full list of supporting configuration options, see @@ -230,12 +242,13 @@ public function setClientConfig(string|array $clientConfig): self } /** - * @param FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials + * @param string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * * @return $this */ - public function setCredentials(FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials): self - { + public function setCredentials( + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials + ): self { $this->credentials = $credentials; return $this; diff --git a/Gax/src/PageStreamingDescriptor.php b/Gax/src/PageStreamingDescriptor.php index f68b7372e80f..b7c939984da2 100644 --- a/Gax/src/PageStreamingDescriptor.php +++ b/Gax/src/PageStreamingDescriptor.php @@ -40,7 +40,7 @@ */ class PageStreamingDescriptor { - private $descriptor; + private array $descriptor; /** * @param array $descriptor { @@ -73,7 +73,7 @@ public function __construct(array $descriptor) * } * @return PageStreamingDescriptor */ - public static function createFromFields(array $fields) + public static function createFromFields(array $fields): self { $requestPageToken = $fields['requestPageTokenField']; $responsePageToken = $fields['responsePageTokenField']; @@ -95,12 +95,12 @@ public static function createFromFields(array $fields) return new PageStreamingDescriptor($descriptor); } - private static function getMethod(string $field) + private static function getMethod(string $field): string { return 'get' . ucfirst($field); } - private static function setMethod(string $field) + private static function setMethod(string $field): string { return 'set' . ucfirst($field); } @@ -108,23 +108,23 @@ private static function setMethod(string $field) /** * @return string The page token get method on the request object */ - public function getRequestPageTokenGetMethod() + public function getRequestPageTokenGetMethod(): string { return $this->descriptor['requestPageTokenGetMethod']; } /** - * @return string The page size get method on the request object + * @return string|null The page size get method on the request object */ - public function getRequestPageSizeGetMethod() + public function getRequestPageSizeGetMethod(): ?string { - return $this->descriptor['requestPageSizeGetMethod']; + return $this->descriptor['requestPageSizeGetMethod'] ?? null; } /** * @return bool True if the request object has a page size field */ - public function requestHasPageSizeField() + public function requestHasPageSizeField(): bool { return array_key_exists('requestPageSizeGetMethod', $this->descriptor); } @@ -132,7 +132,7 @@ public function requestHasPageSizeField() /** * @return string The page token get method on the response object */ - public function getResponsePageTokenGetMethod() + public function getResponsePageTokenGetMethod(): string { return $this->descriptor['responsePageTokenGetMethod']; } @@ -140,7 +140,7 @@ public function getResponsePageTokenGetMethod() /** * @return string The resources get method on the response object */ - public function getResourcesGetMethod() + public function getResourcesGetMethod(): string { return $this->descriptor['resourcesGetMethod']; } @@ -148,20 +148,20 @@ public function getResourcesGetMethod() /** * @return string The page token set method on the request object */ - public function getRequestPageTokenSetMethod() + public function getRequestPageTokenSetMethod(): string { return $this->descriptor['requestPageTokenSetMethod']; } /** - * @return string The page size set method on the request object + * @return string|null The page size set method on the request object */ - public function getRequestPageSizeSetMethod() + public function getRequestPageSizeSetMethod(): ?string { - return $this->descriptor['requestPageSizeSetMethod']; + return $this->descriptor['requestPageSizeSetMethod'] ?? null; } - private static function validate(array $descriptor) + private static function validate(array $descriptor): void { $requiredFields = [ 'requestPageTokenGetMethod', diff --git a/Gax/src/PathTemplate.php b/Gax/src/PathTemplate.php index ac42476de2a8..8864e5734878 100644 --- a/Gax/src/PathTemplate.php +++ b/Gax/src/PathTemplate.php @@ -48,7 +48,7 @@ */ class PathTemplate implements ResourceTemplateInterface { - private $resourceTemplate; + private ResourceTemplateInterface $resourceTemplate; /** * PathTemplate constructor. @@ -56,7 +56,7 @@ class PathTemplate implements ResourceTemplateInterface * @param string $path A path template string * @throws ValidationException When $path cannot be parsed into a valid PathTemplate */ - public function __construct(?string $path = null) + public function __construct(string $path) { if (empty($path)) { throw new ValidationException('Cannot construct PathTemplate from empty string'); @@ -72,7 +72,7 @@ public function __construct(?string $path = null) /** * @return string A string representation of the path template */ - public function __toString() + public function __toString(): string { return $this->resourceTemplate->__toString(); } @@ -85,7 +85,7 @@ public function __toString() * can't be parsed. * @return string A rendered representation of this path template. */ - public function render(array $bindings, bool $urlEncode = false) + public function render(array $bindings, bool $urlEncode = false): string { return $this->resourceTemplate->render($bindings, $urlEncode); } @@ -96,7 +96,7 @@ public function render(array $bindings, bool $urlEncode = false) * @param string $path A resource string. * @return bool */ - public function matches(string $path) + public function matches(string $path): bool { return $this->resourceTemplate->matches($path); } @@ -108,7 +108,7 @@ public function matches(string $path) * @throws ValidationException if path can't be matched to the template. * @return array Array matching var names to binding values. */ - public function match(string $path) + public function match(string $path): array { return $this->resourceTemplate->match($path); } diff --git a/Gax/src/RequestBuilder.php b/Gax/src/RequestBuilder.php index 93678a4503a9..d4fb3d560c74 100644 --- a/Gax/src/RequestBuilder.php +++ b/Gax/src/RequestBuilder.php @@ -52,8 +52,8 @@ class RequestBuilder use UriTrait; use ValidationTrait; - protected $baseUri; - private $restConfig; + protected string $baseUri; + private array $restConfig; /** * @param string $baseUri @@ -71,7 +71,7 @@ public function __construct(string $baseUri, string $restConfigPath) * @param string $path * @return bool */ - public function pathExists(string $path) + public function pathExists(string $path): bool { list($interface, $method) = explode('/', $path); return isset($this->restConfig['interfaces'][$interface][$method]); @@ -84,7 +84,7 @@ public function pathExists(string $path) * @return RequestInterface * @throws ValidationException */ - public function build(string $path, Message $message, array $headers = []) + public function build(string $path, Message $message, array $headers = []): RequestInterface { list($interface, $method) = explode('/', $path); @@ -144,7 +144,7 @@ public function build(string $path, Message $message, array $headers = []) * @param array $config * @return array[] An array of configs */ - private function getConfigsForUriTemplates(array $config) + private function getConfigsForUriTemplates(array $config): array { $configs = [$config]; @@ -162,7 +162,7 @@ private function getConfigsForUriTemplates(array $config) * @param array $config * @return array Tuple [$body, $queryParams] */ - private function constructBodyAndQueryParameters(Message $message, array $config) + private function constructBodyAndQueryParameters(Message $message, array $config): array { $messageDataJson = $message->serializeToJsonString(); @@ -229,7 +229,7 @@ private function constructBodyAndQueryParameters(Message $message, array $config * @param Message $message * @return array Bindings from path template fields to values from message */ - private function buildBindings(array $placeholders, Message $message) + private function buildBindings(array $placeholders, Message $message): array { $bindings = []; foreach ($placeholders as $placeholder => $metadata) { @@ -256,7 +256,7 @@ function (?Message $result = null, $getter = null) { * @return null|string * @throws ValidationException */ - private function tryRenderPathTemplate(string $uriTemplate, array $bindings) + private function tryRenderPathTemplate(string $uriTemplate, array $bindings): ?string { $template = new AbsoluteResourceTemplate($uriTemplate); @@ -272,7 +272,7 @@ private function tryRenderPathTemplate(string $uriTemplate, array $bindings) * @param array $queryParams * @return UriInterface */ - protected function buildUri(string $path, array $queryParams) + protected function buildUri(string $path, array $queryParams): UriInterface { $uri = Utils::uriFor( sprintf( diff --git a/Gax/src/RequestParamsHeaderDescriptor.php b/Gax/src/RequestParamsHeaderDescriptor.php index fca3c5426f5f..90d17df8bb1e 100644 --- a/Gax/src/RequestParamsHeaderDescriptor.php +++ b/Gax/src/RequestParamsHeaderDescriptor.php @@ -41,10 +41,7 @@ class RequestParamsHeaderDescriptor { const HEADER_KEY = 'x-goog-request-params'; - /** - * @var array - */ - private $header; + private array $header; /** * RequestParamsHeaderDescriptor constructor. @@ -73,7 +70,7 @@ public function __construct(array $requestParams) * * @return array */ - public function getHeader() + public function getHeader(): array { return $this->header; } diff --git a/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php b/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php index 3b26b02f7749..16de78aed1fc 100644 --- a/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php +++ b/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php @@ -56,8 +56,7 @@ class AbsoluteResourceTemplate implements ResourceTemplateInterface { private RelativeResourceTemplate $resourceTemplate; - /** @var string */ - private $verb; + private string $verb; /** * AbsoluteResourceTemplate constructor. @@ -82,7 +81,7 @@ public function __construct(string $path) /** * @inheritdoc */ - public function __toString() + public function __toString(): string { return sprintf('/%s%s', $this->resourceTemplate, $this->renderVerb()); } @@ -90,7 +89,7 @@ public function __toString() /** * @inheritdoc */ - public function render(array $bindings, bool $urlEncode = false) + public function render(array $bindings, bool $urlEncode = false): string { return sprintf('/%s%s', $this->resourceTemplate->render($bindings, $urlEncode), $this->renderVerb()); } @@ -98,7 +97,7 @@ public function render(array $bindings, bool $urlEncode = false) /** * @inheritdoc */ - public function matches(string $path) + public function matches(string $path): bool { try { $this->match($path); @@ -111,7 +110,7 @@ public function matches(string $path) /** * @inheritdoc */ - public function match(string $path) + public function match(string $path): array { if (empty($path)) { throw $this->matchException($path, 'path cannot be empty'); @@ -126,17 +125,17 @@ public function match(string $path) return $this->resourceTemplate->match(substr($path, 1, $verbSeparatorPos - 1)); } - private function matchException(string $path, string $reason) + private function matchException(string $path, string $reason): ValidationException { return new ValidationException("Could not match path '$path' to template '$this': $reason"); } - private function renderVerb() + private function renderVerb(): string { return $this->verb ? ':' . $this->verb : ''; } - private function verbSeparatorPos(string $path) + private function verbSeparatorPos(string $path): int { $finalSeparatorPos = strrpos($path, '/'); $verbSeparatorPos = strrpos($path, ':', $finalSeparatorPos); diff --git a/Gax/src/ResourceTemplate/Parser.php b/Gax/src/ResourceTemplate/Parser.php index 7d916ede402a..aa74e1c3dc3d 100644 --- a/Gax/src/ResourceTemplate/Parser.php +++ b/Gax/src/ResourceTemplate/Parser.php @@ -50,7 +50,7 @@ class Parser * @return array * @throws ValidationException */ - public static function parseSegments(?string $path = null) + public static function parseSegments(?string $path = null): array { if (empty($path)) { throw new ValidationException('Cannot parse empty path'); @@ -76,7 +76,7 @@ public static function parseSegments(?string $path = null) * @return Segment * @throws ValidationException */ - private static function parseSegmentFromPath(string $path, string &$nextLiteral, int &$index) + private static function parseSegmentFromPath(string $path, string &$nextLiteral, int &$index): Segment { if ($index >= strlen($path)) { // A trailing '/' has caused the index to exceed the bounds @@ -135,7 +135,7 @@ private static function parseSegmentFromPath(string $path, string &$nextLiteral, * @return Segment * @throws ValidationException */ - private static function parse(string $segmentString, string $path, int $index) + private static function parse(string $segmentString, string $path, int $index): Segment { if ($segmentString === '*') { return new Segment(Segment::WILDCARD_SEGMENT); @@ -160,7 +160,7 @@ private static function parse(string $segmentString, string $path, int $index) * @return Segment * @throws ValidationException */ - private static function parseVariableSegment(string $segmentStringWithoutBraces, string $separatorLiteral) + private static function parseVariableSegment(string $segmentStringWithoutBraces, string $separatorLiteral): Segment { // Validate there are no nested braces $nestedOpenBracket = strpos($segmentStringWithoutBraces, '{'); @@ -196,7 +196,7 @@ private static function parseVariableSegment(string $segmentStringWithoutBraces, * @return string * @throws ValidationException */ - private static function parseLiteralFromPath(string $literal, string $path, int &$index) + private static function parseLiteralFromPath(string $literal, string $path, int &$index): string { $literalLength = strlen($literal); if (strlen($path) < ($index + $literalLength)) { @@ -210,7 +210,7 @@ private static function parseLiteralFromPath(string $literal, string $path, int return $consumedLiteral; } - private static function parseError(string $path, int $index, string $reason) + private static function parseError(string $path, int $index, string $reason): ValidationException { return new ValidationException("Error parsing '$path' at index $index: $reason"); } @@ -222,7 +222,7 @@ private static function parseError(string $path, int $index, string $reason) * @param string $literal * @return bool */ - private static function isValidLiteral(string $literal) + private static function isValidLiteral(string $literal): bool { return preg_match('/^[0-9a-zA-Z\\.\\-~_]+$/', $literal) === 1; } diff --git a/Gax/src/ResourceTemplate/RelativeResourceTemplate.php b/Gax/src/ResourceTemplate/RelativeResourceTemplate.php index 1e7d64f6afa0..32e19f8a42e0 100644 --- a/Gax/src/ResourceTemplate/RelativeResourceTemplate.php +++ b/Gax/src/ResourceTemplate/RelativeResourceTemplate.php @@ -95,7 +95,7 @@ public function __construct(string $path) /** * @inheritdoc */ - public function __toString() + public function __toString(): string { return self::renderSegments($this->segments); } @@ -103,7 +103,7 @@ public function __toString() /** * @inheritdoc */ - public function render(array $bindings, bool $urlEncode = false) + public function render(array $bindings, bool $urlEncode = false): string { $literalSegments = []; $keySegmentTuples = self::buildKeySegmentTuples($this->segments); @@ -199,7 +199,7 @@ private static function validateDotSegments(int $segmentType, string $value, str /** * @inheritdoc */ - public function matches(string $path) + public function matches(string $path): bool { try { $this->match($path); @@ -212,7 +212,7 @@ public function matches(string $path) /** * @inheritdoc */ - public function match(string $path) + public function match(string $path): array { // High level strategy for matching: // - Build a list of Segments from our template, where any variable segments are @@ -333,12 +333,12 @@ public function match(string $path) return $collapsedBindings; } - private function matchException(string $path, string $reason) + private function matchException(string $path, string $reason): ValidationException { return new ValidationException("Could not match path '$path' to template '$this': $reason"); } - private function renderingException(array $bindings, string $reason) + private function renderingException(array $bindings, string $reason): ValidationException { $bindingsString = print_r($bindings, true); return new ValidationException( @@ -352,7 +352,7 @@ private function renderingException(array $bindings, string $reason) * @param string|null $separator An optional string separator * @return array[] A list of [string, Segment] tuples */ - private static function buildKeySegmentTuples(array $segments, ?string $separator = null) + private static function buildKeySegmentTuples(array $segments, ?string $separator = null): array { $keySegmentTuples = []; $positionalArgumentCounter = 0; @@ -385,7 +385,7 @@ private static function buildKeySegmentTuples(array $segments, ?string $separato * @param array[] $keySegmentTuples A list of [string, Segment] tuples * @return array[] A list of [string, Segment] tuples */ - private static function flattenKeySegmentTuples(array $keySegmentTuples) + private static function flattenKeySegmentTuples(array $keySegmentTuples): array { $flattenedKeySegmentTuples = []; foreach ($keySegmentTuples as list($key, $segment)) { @@ -419,7 +419,7 @@ private static function flattenKeySegmentTuples(array $keySegmentTuples) * @param Segment[] $segments * @return int */ - private static function countDoubleWildcards(array $segments) + private static function countDoubleWildcards(array $segments): int { $doubleWildcardCount = 0; foreach ($segments as $segment) { @@ -440,7 +440,7 @@ private static function countDoubleWildcards(array $segments) * @param array $segmentsToRender * @return string */ - private static function renderSegments(array $segmentsToRender) + private static function renderSegments(array $segmentsToRender): string { $renderResult = ''; for ($i = 0; $i < count($segmentsToRender); $i++) { @@ -458,7 +458,7 @@ private static function renderSegments(array $segmentsToRender) * @param string $value * @return string */ - private static function encodeValue(string $value) + private static function encodeValue(string $value): string { $segments = explode('/', $value); $encodedSegments = array_map('rawurlencode', $segments); diff --git a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php index d5cb1357f519..bcdd9ab2728e 100644 --- a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php +++ b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php @@ -60,17 +60,18 @@ interface ResourceTemplateInterface /** * @return string A string representation of the resource template */ - public function __toString(); + public function __toString(): string; /** * Renders a resource template using the provided bindings. * * @param array $bindings An array matching var names to binding strings. + * @param bool $urlEncode * @return string A rendered representation of this resource template. * @throws ValidationException If $bindings does not contain all required keys * or if a sub-template can't be parsed. */ - public function render(array $bindings); + public function render(array $bindings, bool $urlEncode = false): string; /** * Check if $path matches a resource string. @@ -78,7 +79,7 @@ public function render(array $bindings); * @param string $path A resource string. * @return bool */ - public function matches(string $path); + public function matches(string $path): bool; /** * Matches a given $path to a resource template, and returns an array of bindings between @@ -89,5 +90,5 @@ public function matches(string $path); * @throws ValidationException if path can't be matched to the template. * @return array Array matching var names to binding values. */ - public function match(string $path); + public function match(string $path): array; } diff --git a/Gax/src/ResourceTemplate/Segment.php b/Gax/src/ResourceTemplate/Segment.php index 342c8c04fbfc..54df464dad36 100644 --- a/Gax/src/ResourceTemplate/Segment.php +++ b/Gax/src/ResourceTemplate/Segment.php @@ -101,7 +101,7 @@ public function __construct( /** * @return string A string representation of the segment. */ - public function __toString() + public function __toString(): string { return $this->stringRepr; } @@ -113,7 +113,7 @@ public function __toString() * @return bool * @throws ValidationException */ - public function matches(string $value) + public function matches(string $value): bool { switch ($this->segmentType) { case Segment::LITERAL_SEGMENT: @@ -134,7 +134,7 @@ public function matches(string $value) /** * @return int */ - public function getSegmentType() + public function getSegmentType(): int { return $this->segmentType; } @@ -142,7 +142,7 @@ public function getSegmentType() /** * @return string|null */ - public function getKey() + public function getKey(): ?string { return $this->key; } @@ -150,7 +150,7 @@ public function getKey() /** * @return string|null */ - public function getValue() + public function getValue(): ?string { return $this->value; } @@ -158,7 +158,7 @@ public function getValue() /** * @return RelativeResourceTemplate|null */ - public function getTemplate() + public function getTemplate(): ?RelativeResourceTemplate { return $this->template; } @@ -166,7 +166,7 @@ public function getTemplate() /** * @return string */ - public function getSeparator() + public function getSeparator(): string { return $this->separator; } @@ -178,7 +178,7 @@ public function getSeparator() * @param string $binding * @return bool */ - private static function isValidBinding(string $binding) + private static function isValidBinding(string $binding): bool { return preg_match('-^[^/]+$-', $binding) === 1; } @@ -190,7 +190,7 @@ private static function isValidBinding(string $binding) * @param string $binding * @return bool */ - private static function isValidDoubleWildcardBinding(string $binding) + private static function isValidDoubleWildcardBinding(string $binding): bool { return preg_match('-^.+$-', $binding) === 1; } diff --git a/Gax/src/ResumableUpload/ResumableUploadClient.php b/Gax/src/ResumableUpload/ResumableUploadClient.php index 1f4477db4d4c..d29f9e5704ea 100644 --- a/Gax/src/ResumableUpload/ResumableUploadClient.php +++ b/Gax/src/ResumableUpload/ResumableUploadClient.php @@ -488,7 +488,7 @@ private function sendRequest( $response = $this->transport->sendRawRequest($request, $callOptions); } - if (is_object($response) && method_exists($response, 'wait')) { + if (method_exists($response, 'wait')) { $response = $response->wait(); } return $response; diff --git a/Gax/src/ResumableUpload/ResumableUploadTransportInterface.php b/Gax/src/ResumableUpload/ResumableUploadTransportInterface.php index f059b2b663c4..74bfcd90e1ed 100644 --- a/Gax/src/ResumableUpload/ResumableUploadTransportInterface.php +++ b/Gax/src/ResumableUpload/ResumableUploadTransportInterface.php @@ -53,7 +53,7 @@ interface ResumableUploadTransportInterface * @param array $options * @return ResponseInterface|PromiseInterface */ - public function sendRawRequest(RequestInterface $request, array $options = []); + public function sendRawRequest(RequestInterface $request, array $options = []): ResponseInterface|PromiseInterface; /** * Builds a PSR-7 request. diff --git a/Gax/src/Serializer.php b/Gax/src/Serializer.php index eb84356b5645..35f193a9b318 100644 --- a/Gax/src/Serializer.php +++ b/Gax/src/Serializer.php @@ -38,6 +38,8 @@ use Google\Protobuf\Descriptor; use Google\Protobuf\DescriptorPool; use Google\Protobuf\FieldDescriptor; +use Google\Protobuf\Internal\GPBLabel; +use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\Message; use Google\Rpc\BadRequest; use Google\Rpc\DebugInfo; @@ -60,24 +62,24 @@ class Serializer const MAP_KEY_FIELD_NAME = 'key'; const MAP_VALUE_FIELD_NAME = 'value'; - private static $phpArraySerializer; + private static ?Serializer $phpArraySerializer = null; // Caches for different helper functions private static array $getterMap = []; private static array $setterMap = []; private static array $snakeCaseMap = []; private static array $camelCaseMap = []; - private $fieldTransformers; - private $messageTypeTransformers; - private $decodeFieldTransformers; - private $decodeMessageTypeTransformers; + private array $fieldTransformers; + private array $messageTypeTransformers; + private array $decodeFieldTransformers; + private array $decodeMessageTypeTransformers; // Array of key-value pairs which specify a custom encoding function. // The key is the proto class and the value is the function // which will be used to convert the proto instead of the // encodeMessage method from the Serializer class. - private $customEncoders; + private array $customEncoders; - private $descriptorMaps = []; + private array $descriptorMaps = []; /** * Serializer constructor. @@ -86,13 +88,14 @@ class Serializer * @param array $messageTypeTransformers An array mapping message names to transformation functions * @param array $decodeFieldTransformers An array mapping field names to transformation functions * @param array $decodeMessageTypeTransformers An array mapping message names to transformation functions + * @param array $customEncoders An array mapping message classes to custom encoding functions */ public function __construct( - $fieldTransformers = [], - $messageTypeTransformers = [], - $decodeFieldTransformers = [], - $decodeMessageTypeTransformers = [], - $customEncoders = [], + array $fieldTransformers = [], + array $messageTypeTransformers = [], + array $decodeFieldTransformers = [], + array $decodeMessageTypeTransformers = [], + array $customEncoders = [], ) { $this->fieldTransformers = $fieldTransformers; $this->messageTypeTransformers = $messageTypeTransformers; @@ -104,11 +107,11 @@ public function __construct( /** * Encode protobuf message as a PHP array * - * @param mixed $message + * @param Message $message * @return array * @throws ValidationException */ - public function encodeMessage($message) + public function encodeMessage(Message $message): array { $cls = get_class($message); @@ -135,12 +138,12 @@ public function encodeMessage($message) /** * Decode PHP array into the specified protobuf message * - * @param mixed $message + * @param Message $message * @param array $data - * @return mixed + * @return Message * @throws ValidationException */ - public function decodeMessage($message, array $data) + public function decodeMessage(Message $message, array $data): Message { // Get message descriptor $pool = DescriptorPool::getGeneratedPool(); @@ -161,7 +164,7 @@ public function decodeMessage($message, array $data) * @return string Json representation of $message * @throws ValidationException */ - public static function serializeToJson(Message $message) + public static function serializeToJson(Message $message): string { return json_encode(self::serializeToPhpArray($message), JSON_PRETTY_PRINT); } @@ -171,7 +174,7 @@ public static function serializeToJson(Message $message) * @return array PHP array representation of $message * @throws ValidationException */ - public static function serializeToPhpArray(Message $message) + public static function serializeToPhpArray(Message $message): array { return self::getPhpArraySerializer()->encodeMessage($message); } @@ -183,7 +186,7 @@ public static function serializeToPhpArray(Message $message) * @param null|array $errors * @return array */ - public static function decodeMetadata(array $metadata, ?array &$errors = null) + public static function decodeMetadata(array $metadata, ?array &$errors = null): array { if (count($metadata) == 0) { return []; @@ -267,7 +270,7 @@ public static function decodeMetadata(array $metadata, ?array &$errors = null) * @param iterable $anyArray * @return array */ - public static function decodeAnyMessages($anyArray) + public static function decodeAnyMessages(iterable $anyArray): array { $results = []; foreach ($anyArray as $any) { @@ -289,11 +292,11 @@ public static function decodeAnyMessages($anyArray) /** * @param FieldDescriptor $field - * @param Message|array|string $data + * @param mixed $data * @return mixed * @throws \Exception */ - private function encodeElement(FieldDescriptor $field, $data) + private function encodeElement(FieldDescriptor $field, mixed $data): mixed { switch ($field->getType()) { case GPBType::MESSAGE: @@ -318,7 +321,7 @@ private function encodeElement(FieldDescriptor $field, $data) return $result; } - private function getDescriptorMaps(Descriptor $descriptor) + private function getDescriptorMaps(Descriptor $descriptor): array { if (!isset($this->descriptorMaps[$descriptor->getFullName()])) { $fieldsByName = []; @@ -348,7 +351,7 @@ private function getDescriptorMaps(Descriptor $descriptor) * @return array * @throws \Exception */ - private function encodeMessageImpl(Message $message, Descriptor $messageType) + private function encodeMessageImpl(Message $message, Descriptor $messageType): array { $data = []; @@ -405,7 +408,7 @@ private function encodeMessageImpl(Message $message, Descriptor $messageType) * @return mixed * @throws \Exception */ - private function decodeElement(FieldDescriptor $field, $data) + private function decodeElement(FieldDescriptor $field, mixed $data): mixed { if (isset($this->decodeFieldTransformers[$field->getName()])) { $data = $this->decodeFieldTransformers[$field->getName()]($data); @@ -434,10 +437,10 @@ private function decodeElement(FieldDescriptor $field, $data) * @param Message $message * @param Descriptor $messageType * @param array $data - * @return mixed + * @return Message * @throws \Exception */ - private function decodeMessageImpl(Message $message, Descriptor $messageType, array $data) + private function decodeMessageImpl(Message $message, Descriptor $messageType, array $data): Message { list($fieldsByName, $_) = $this->getDescriptorMaps($messageType); foreach ($data as $key => $v) { @@ -505,7 +508,7 @@ private function checkFieldRepeated(FieldDescriptor $field): bool * @param string $name * @return string Getter function */ - public static function getGetter(string $name) + public static function getGetter(string $name): string { if (!isset(self::$getterMap[$name])) { self::$getterMap[$name] = 'get' . ucfirst(self::toCamelCase($name)); @@ -517,7 +520,7 @@ public static function getGetter(string $name) * @param string $name * @return string Setter function */ - public static function getSetter(string $name) + public static function getSetter(string $name): string { if (!isset(self::$setterMap[$name])) { self::$setterMap[$name] = 'set' . ucfirst(self::toCamelCase($name)); @@ -531,7 +534,7 @@ public static function getSetter(string $name) * @param string $key * @return string */ - public static function toSnakeCase(string $key) + public static function toSnakeCase(string $key): string { if (!isset(self::$snakeCaseMap[$key])) { self::$snakeCaseMap[$key] = strtolower( @@ -547,7 +550,7 @@ public static function toSnakeCase(string $key) * @param string $key * @return string */ - public static function toCamelCase(string $key) + public static function toCamelCase(string $key): string { if (!isset(self::$camelCaseMap[$key])) { self::$camelCaseMap[$key] = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key)))); @@ -555,12 +558,12 @@ public static function toCamelCase(string $key) return self::$camelCaseMap[$key]; } - private static function hasBinaryHeaderSuffix(string $key) + private static function hasBinaryHeaderSuffix(string $key): bool { return substr_compare($key, '-bin', strlen($key) - 4) === 0; } - private static function getPhpArraySerializer() + private static function getPhpArraySerializer(): Serializer { if (is_null(self::$phpArraySerializer)) { self::$phpArraySerializer = new Serializer(); @@ -568,7 +571,7 @@ private static function getPhpArraySerializer() return self::$phpArraySerializer; } - public static function loadKnownMetadataTypes() + public static function loadKnownMetadataTypes(): void { foreach (KnownTypes::allKnownTypes() as $key => $class) { new $class(); diff --git a/Gax/src/ServerStreamingCallInterface.php b/Gax/src/ServerStreamingCallInterface.php index ae8cc3ed50fe..26f81276d188 100644 --- a/Gax/src/ServerStreamingCallInterface.php +++ b/Gax/src/ServerStreamingCallInterface.php @@ -34,12 +34,14 @@ namespace Google\ApiCore; +use Generator; +use stdClass; + /** * @internal */ interface ServerStreamingCallInterface { - /** * Start the call. * @@ -50,41 +52,41 @@ interface ServerStreamingCallInterface * 'flags' => a number (optional) * @return void */ - public function start($data, array $metadata = [], array $options = []); + public function start(mixed $data, array $metadata = [], array $options = []): void; /** - * @return mixed An iterator of response values. + * @return Generator An iterator of response values. */ - public function responses(); + public function responses(): Generator; /** * Return the status of the server stream. * - * @return \stdClass The API status. + * @return ?stdClass The API status. */ - public function getStatus(); + public function getStatus(): ?stdClass; /** * @return mixed The metadata sent by the server. */ - public function getMetadata(); + public function getMetadata(): mixed; /** * @return mixed The trailing metadata sent by the server. */ - public function getTrailingMetadata(); + public function getTrailingMetadata(): mixed; /** - * @return string The URI of the endpoint. + * @return ?string The URI of the endpoint. */ - public function getPeer(); + public function getPeer(): ?string; /** * Cancels the call. * * @return void */ - public function cancel(); + public function cancel(): void; /** * Set the CallCredentials for the underlying Call. @@ -93,5 +95,5 @@ public function cancel(); * * @return void */ - public function setCallCredentials($call_credentials); + public function setCallCredentials(mixed $call_credentials): void; } diff --git a/Gax/src/Testing/MockBidiStreamingCall.php b/Gax/src/Testing/MockBidiStreamingCall.php index 359840edad94..b42903b1186b 100644 --- a/Gax/src/Testing/MockBidiStreamingCall.php +++ b/Gax/src/Testing/MockBidiStreamingCall.php @@ -50,10 +50,10 @@ class MockBidiStreamingCall extends Grpc\BidiStreamingCall { use SerializationTrait; - private $responses; - private $status; - private $writesDone = false; - private $receivedWrites = []; + private array $responses; + private stdClass $status; + private bool $writesDone = false; + private array $receivedWrites = []; /** * MockBidiStreamingCall constructor. @@ -61,7 +61,7 @@ class MockBidiStreamingCall extends Grpc\BidiStreamingCall * @param mixed|null $deserialize An optional deserialize method for the response object. * @param stdClass|null $status An optional status object. If set to null, a status of OK is used. */ - public function __construct(array $responses, $deserialize = null, ?stdClass $status = null) + public function __construct(array $responses, mixed $deserialize = null, ?stdClass $status = null) { $this->responses = $responses; $this->deserialize = $deserialize; @@ -75,7 +75,7 @@ public function __construct(array $responses, $deserialize = null, ?stdClass $st * @return mixed|null * @throws ApiException */ - public function read() + public function read(): mixed { if (count($this->responses) > 0) { $resp = array_shift($this->responses); @@ -102,10 +102,10 @@ public function read() } /** - * @return stdClass|null + * @return stdClass * @throws ApiException */ - public function getStatus() + public function getStatus(): stdClass { if (count($this->responses) > 0) { throw new ApiException( @@ -130,7 +130,7 @@ public function getStatus() * @param array $options An array of options. * @throws ApiException */ - public function write($request, array $options = []) + public function write($request, array $options = []): void { if ($this->writesDone) { throw new ApiException( @@ -151,7 +151,7 @@ public function write($request, array $options = []) /** * Set writesDone to true */ - public function writesDone() + public function writesDone(): void { $this->writesDone = true; } @@ -161,7 +161,7 @@ public function writesDone() * * @return mixed[] An array of received requests */ - public function popReceivedCalls() + public function popReceivedCalls(): array { $receivedFuncCallsTemp = $this->receivedWrites; $this->receivedWrites = []; diff --git a/Gax/src/Testing/MockClientStreamingCall.php b/Gax/src/Testing/MockClientStreamingCall.php index 3abfd22477a6..e493126398df 100644 --- a/Gax/src/Testing/MockClientStreamingCall.php +++ b/Gax/src/Testing/MockClientStreamingCall.php @@ -54,17 +54,17 @@ */ class MockClientStreamingCall extends Grpc\ClientStreamingCall { - private $mockUnaryCall; - private $waitCalled = false; - private $receivedWrites = []; + private MockUnaryCall $mockUnaryCall; + private bool $waitCalled = false; + private array $receivedWrites = []; /** * MockClientStreamingCall constructor. - * @param Message|string $response The response object. + * @param Message|string|mixed $response The response object. * @param callable|array|null $deserialize An optional deserialize method for the response object. * @param stdClass|null $status An optional status object. If set to null, a status of OK is used. */ - public function __construct($response, $deserialize = null, ?stdClass $status = null) + public function __construct(mixed $response, mixed $deserialize = null, ?stdClass $status = null) { $this->mockUnaryCall = new MockUnaryCall($response, $deserialize, $status); } @@ -73,7 +73,7 @@ public function __construct($response, $deserialize = null, ?stdClass $status = * Immediately return the preset response object and status. * @return array The response object and status. */ - public function wait() + public function wait(): array { $this->waitCalled = true; return $this->mockUnaryCall->wait(); @@ -85,7 +85,7 @@ public function wait() * @param array $options An array of options * @throws ApiException */ - public function write($request, array $options = []) + public function write($request, array $options = []): void { if ($this->waitCalled) { throw new ApiException('Cannot call write() after wait()', Code::INTERNAL, ApiStatus::INTERNAL); @@ -104,7 +104,7 @@ public function write($request, array $options = []) * * @return mixed[] An array of received requests */ - public function popReceivedCalls() + public function popReceivedCalls(): array { $receivedFuncCallsTemp = $this->receivedWrites; $this->receivedWrites = []; diff --git a/Gax/src/Testing/MockServerStreamingCall.php b/Gax/src/Testing/MockServerStreamingCall.php index f3ab92a0e56a..744ee9edca71 100644 --- a/Gax/src/Testing/MockServerStreamingCall.php +++ b/Gax/src/Testing/MockServerStreamingCall.php @@ -34,6 +34,7 @@ namespace Google\ApiCore\Testing; +use Generator; use Google\ApiCore\ApiException; use Google\ApiCore\ApiStatus; use Google\ApiCore\ServerStreamingCallInterface; @@ -50,8 +51,8 @@ class MockServerStreamingCall extends \Grpc\ServerStreamingCall implements Serve { use SerializationTrait; - private $responses; - private $status; + private array $responses; + private stdClass $status; /** * MockServerStreamingCall constructor. @@ -59,7 +60,7 @@ class MockServerStreamingCall extends \Grpc\ServerStreamingCall implements Serve * @param callable|array|null $deserialize An optional deserialize method for the response object. * @param stdClass|null $status An optional status object. If set to null, a status of OK is used. */ - public function __construct(array $responses, $deserialize = null, ?stdClass $status = null) + public function __construct(array $responses, mixed $deserialize = null, ?stdClass $status = null) { $this->responses = $responses; $this->deserialize = $deserialize; @@ -73,7 +74,12 @@ public function __construct(array $responses, $deserialize = null, ?stdClass $st $this->status = $status; } - public function responses() + public function start(mixed $data, array $metadata = [], array $options = []): void + { + parent::start($data, $metadata, $options); + } + + public function responses(): Generator { while (count($this->responses) > 0) { $resp = array_shift($this->responses); @@ -86,7 +92,7 @@ public function responses() * @return stdClass|null * @throws ApiException */ - public function getStatus() + public function getStatus(): ?stdClass { if (count($this->responses) > 0) { throw new ApiException( @@ -97,4 +103,29 @@ public function getStatus() } return $this->status; } + + public function getMetadata(): mixed + { + return $this->metadata; + } + + public function getTrailingMetadata(): mixed + { + return $this->trailing_metadata; + } + + public function getPeer(): ?string + { + return parent::getPeer(); + } + + public function cancel(): void + { + parent::cancel(); + } + + public function setCallCredentials(mixed $call_credentials): void + { + parent::setCallCredentials($call_credentials); + } } diff --git a/Gax/src/Testing/MockStatus.php b/Gax/src/Testing/MockStatus.php index 78354bc0bb07..b2ffd89a951e 100644 --- a/Gax/src/Testing/MockStatus.php +++ b/Gax/src/Testing/MockStatus.php @@ -43,10 +43,10 @@ class MockStatus extends stdClass { /** @var Code|int $code */ - public $code; - public $details; - public $metadata; - public function __construct($code, ?string $details = null, array $metadata = []) + public int|Code $code; + public ?string $details; + public array $metadata; + public function __construct(int|Code $code, ?string $details = null, array $metadata = []) { $this->code = $code; $this->details = $details; diff --git a/Gax/src/Testing/MockStubTrait.php b/Gax/src/Testing/MockStubTrait.php index 182d14df845b..b4792e0ea428 100644 --- a/Gax/src/Testing/MockStubTrait.php +++ b/Gax/src/Testing/MockStubTrait.php @@ -48,10 +48,11 @@ */ trait MockStubTrait { - private $receivedFuncCalls = []; - private $responses = []; - private $serverStreamingStatus = null; - private $callObjects = []; + private array $receivedFuncCalls = []; + private array $responses = []; + private ?stdClass $serverStreamingStatus = null; + private array $callObjects = []; + /** @var callable|array|null */ private $deserialize; public function __construct(?callable $deserialize = null) @@ -76,7 +77,7 @@ public function _simpleRequest( $deserialize, array $metadata = [], array $options = [] - ) { + ): MockUnaryCall { $this->receivedFuncCalls[] = new ReceivedRequest($method, $argument, $deserialize, $metadata, $options); if (count($this->responses) < 1) { throw new UnderflowException('ran out of responses'); @@ -105,7 +106,7 @@ public function _clientStreamRequest( $deserialize, array $metadata = [], array $options = [] - ) { + ): MockClientStreamingCall { $this->receivedFuncCalls[] = new ReceivedRequest($method, null, $deserialize, $metadata, $options); if (count($this->responses) < 1) { throw new UnderflowException('ran out of responses'); @@ -137,7 +138,7 @@ public function _serverStreamRequest( $deserialize, array $metadata = [], array $options = [] - ) { + ): MockServerStreamingCall { if (is_a($argument, '\Google\Protobuf\Internal\Message')) { /** @var Message $newArgument */ @@ -172,7 +173,7 @@ public function _bidiRequest( $deserialize, array $metadata = [], array $options = [] - ) { + ): MockBidiStreamingCall { $this->receivedFuncCalls[] = new ReceivedRequest($method, null, $deserialize, $metadata, $options); $responses = self::stripStatusFromResponses($this->responses); @@ -182,7 +183,7 @@ public function _bidiRequest( return $call; } - public static function stripStatusFromResponses($responses) + public static function stripStatusFromResponses(array $responses): array { $strippedResponses = []; foreach ($responses as $response) { @@ -195,10 +196,10 @@ public static function stripStatusFromResponses($responses) /** * Add a response object, and an optional status, to the list of responses to be returned via * _simpleRequest. - * @param \Google\Protobuf\Internal\Message $response - * @param stdClass $status + * @param \Google\Protobuf\Internal\Message|mixed $response + * @param stdClass|null $status */ - public function addResponse($response, ?stdClass $status = null) + public function addResponse(mixed $response, ?stdClass $status = null): void { if (!$this->deserialize && $response) { $this->deserialize = [get_class($response), 'decode']; @@ -215,7 +216,7 @@ public function addResponse($response, ?stdClass $status = null) * * @param stdClass $status */ - public function setStreamingStatus(stdClass $status) + public function setStreamingStatus(stdClass $status): void { $this->serverStreamingStatus = $status; } @@ -225,7 +226,7 @@ public function setStreamingStatus(stdClass $status) * * @return ReceivedRequest[] An array of received requests */ - public function popReceivedCalls() + public function popReceivedCalls(): array { $receivedFuncCallsTemp = $this->receivedFuncCalls; $this->receivedFuncCalls = []; @@ -235,7 +236,7 @@ public function popReceivedCalls() /** * @return int The number of calls received. */ - public function getReceivedCallCount() + public function getReceivedCallCount(): int { return count($this->receivedFuncCalls); } @@ -243,7 +244,7 @@ public function getReceivedCallCount() /** * @return mixed[] The call objects created by calls to the stub */ - public function popCallObjects() + public function popCallObjects(): array { $callObjectsTemp = $this->callObjects; $this->callObjects = []; @@ -253,7 +254,7 @@ public function popCallObjects() /** * @return bool True if $receivedFuncCalls and $response are empty. */ - public function isExhausted() + public function isExhausted(): bool { return count($this->receivedFuncCalls) === 0 && count($this->responses) === 0; @@ -262,11 +263,14 @@ public function isExhausted() /** * @param mixed $responseObject * @param stdClass|null $status - * @param callable $deserialize + * @param callable|null $deserialize * @return static An instance of the current class type. */ - public static function create($responseObject, ?stdClass $status = null, ?callable $deserialize = null) - { + public static function create( + mixed $responseObject, + ?stdClass $status = null, + ?callable $deserialize = null + ): static { $stub = new static($deserialize); // @phpstan-ignore-line $stub->addResponse($responseObject, $status); return $stub; @@ -275,12 +279,15 @@ public static function create($responseObject, ?stdClass $status = null, ?callab /** * Creates a sequence such that the responses are returned in order. * @param mixed[] $sequence - * @param callable $deserialize - * @param stdClass $finalStatus + * @param callable|null $deserialize + * @param stdClass|null $finalStatus * @return static An instance of the current class type. */ - public static function createWithResponseSequence(array $sequence, ?callable $deserialize = null, ?stdClass $finalStatus = null) - { + public static function createWithResponseSequence( + array $sequence, + ?callable $deserialize = null, + ?stdClass $finalStatus = null + ): static { $stub = new static($deserialize); // @phpstan-ignore-line foreach ($sequence as $elem) { if (count($elem) == 1) { diff --git a/Gax/src/Testing/MockTransport.php b/Gax/src/Testing/MockTransport.php index 524280ac4110..e82860b63a62 100644 --- a/Gax/src/Testing/MockTransport.php +++ b/Gax/src/Testing/MockTransport.php @@ -42,6 +42,7 @@ use Google\ApiCore\Transport\TransportInterface; use Google\Rpc\Code; use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\PromiseInterface; /** * @internal @@ -50,14 +51,14 @@ class MockTransport implements TransportInterface { use MockStubTrait; - private $agentHeaderDescriptor; // @phpstan-ignore-line + private mixed $agentHeaderDescriptor = null; // @phpstan-ignore-line - public function setAgentHeaderDescriptor($agentHeaderDescriptor) + public function setAgentHeaderDescriptor(mixed $agentHeaderDescriptor): void { $this->agentHeaderDescriptor = $agentHeaderDescriptor; } - public function startUnaryCall(Call $call, array $options) + public function startUnaryCall(Call $call, array $options): PromiseInterface { $call = call_user_func([$this, $call->getMethod()], $call, $options); return $promise = new Promise( @@ -74,28 +75,28 @@ function () use ($call, &$promise) { ); } - public function startBidiStreamingCall(Call $call, array $options) + public function startBidiStreamingCall(Call $call, array $options): BidiStream { $newArgs = ['/' . $call->getMethod(), $this->deserialize, $options, $options]; $response = $this->_bidiRequest(...$newArgs); return new BidiStream($response, $call->getDescriptor()); } - public function startClientStreamingCall(Call $call, array $options) + public function startClientStreamingCall(Call $call, array $options): ClientStream { $newArgs = ['/' . $call->getMethod(), $this->deserialize, $options, $options]; $response = $this->_clientStreamRequest(...$newArgs); return new ClientStream($response, $call->getDescriptor()); } - public function startServerStreamingCall(Call $call, array $options) + public function startServerStreamingCall(Call $call, array $options): ServerStream { $newArgs = ['/' . $call->getMethod(), $call->getMessage(), $this->deserialize, $options, $options]; $response = $this->_serverStreamRequest(...$newArgs); return new ServerStream($response, $call->getDescriptor()); } - public function __call(string $name, array $arguments) + public function __call(string $name, array $arguments): mixed { $call = $arguments[0]; $options = $arguments[1]; @@ -109,7 +110,7 @@ public function __call(string $name, array $arguments) ); } - public function close() + public function close(): void { // does nothing } diff --git a/Gax/src/Testing/MockUnaryCall.php b/Gax/src/Testing/MockUnaryCall.php index 1009df53ff15..47bdf2bd0315 100644 --- a/Gax/src/Testing/MockUnaryCall.php +++ b/Gax/src/Testing/MockUnaryCall.php @@ -52,16 +52,16 @@ class MockUnaryCall extends \Grpc\UnaryCall { use SerializationTrait; - private $response; - private $status; + private mixed $response; + private stdClass $status; /** * MockUnaryCall constructor. - * @param Message|string|null $response The response object. + * @param Message|string|mixed $response The response object. * @param callable|array|null $deserialize An optional deserialize method for the response object. * @param stdClass|null $status An optional status object. If set to null, a status of OK is used. */ - public function __construct($response = null, $deserialize = null, ?stdClass $status = null) + public function __construct(mixed $response = null, mixed $deserialize = null, ?stdClass $status = null) { $this->response = $response; $this->deserialize = $deserialize; @@ -75,7 +75,7 @@ public function __construct($response = null, $deserialize = null, ?stdClass $st * Immediately return the preset response object and status. * @return array The response object and status. */ - public function wait() + public function wait(): array { return [ $this->deserializeMessage($this->response, $this->deserialize), diff --git a/Gax/src/Testing/ReceivedRequest.php b/Gax/src/Testing/ReceivedRequest.php index 0d69e2c0ccda..8227bb76c332 100644 --- a/Gax/src/Testing/ReceivedRequest.php +++ b/Gax/src/Testing/ReceivedRequest.php @@ -41,10 +41,15 @@ */ class ReceivedRequest { - private $actualCall; + private array $actualCall; - public function __construct($funcCall, $requestObject, $deserialize = null, $metadata = [], $options = []) - { + public function __construct( + string $funcCall, + mixed $requestObject, + mixed $deserialize = null, + array $metadata = [], + array $options = [] + ) { $this->actualCall = [ 'funcCall' => $funcCall, 'request' => $requestObject, @@ -54,27 +59,27 @@ public function __construct($funcCall, $requestObject, $deserialize = null, $met ]; } - public function getArray() + public function getArray(): array { return $this->actualCall; } - public function getFuncCall() + public function getFuncCall(): string { return $this->actualCall['funcCall']; } - public function getRequestObject() + public function getRequestObject(): mixed { return $this->actualCall['request']; } - public function getMetadata() + public function getMetadata(): array { return $this->actualCall['metadata']; } - public function getOptions() + public function getOptions(): array { return $this->actualCall['options']; } diff --git a/Gax/src/Testing/SerializationTrait.php b/Gax/src/Testing/SerializationTrait.php index c80c6938a508..a183f4e2533d 100644 --- a/Gax/src/Testing/SerializationTrait.php +++ b/Gax/src/Testing/SerializationTrait.php @@ -40,11 +40,14 @@ */ trait SerializationTrait { + /** @var callable|array|null */ + protected $deserialize = null; + /** * @param mixed $message * @param mixed $deserialize */ - protected function deserializeMessage($message, $deserialize) + protected function deserializeMessage(mixed $message, mixed $deserialize): mixed { if ($message === null) { return null; diff --git a/Gax/src/Transport/Grpc/ForwardingCall.php b/Gax/src/Transport/Grpc/ForwardingCall.php index 12e4a092f6bc..2055155bf9e3 100644 --- a/Gax/src/Transport/Grpc/ForwardingCall.php +++ b/Gax/src/Transport/Grpc/ForwardingCall.php @@ -53,7 +53,7 @@ abstract class ForwardingCall * * @param AbstractCall|ForwardingCall $innerCall */ - public function __construct($innerCall) + public function __construct(AbstractCall|ForwardingCall $innerCall) { $this->innerCall = $innerCall; } @@ -61,7 +61,7 @@ public function __construct($innerCall) /** * @return mixed The metadata sent by the server */ - public function getMetadata() + public function getMetadata(): mixed { return $this->innerCall->getMetadata(); } @@ -69,15 +69,15 @@ public function getMetadata() /** * @return mixed The trailing metadata sent by the server */ - public function getTrailingMetadata() + public function getTrailingMetadata(): mixed { return $this->innerCall->getTrailingMetadata(); } /** - * @return string The URI of the endpoint + * @return ?string The URI of the endpoint */ - public function getPeer() + public function getPeer(): ?string { return $this->innerCall->getPeer(); } @@ -85,7 +85,7 @@ public function getPeer() /** * Cancels the call. */ - public function cancel() + public function cancel(): void { $this->innerCall->cancel(); } diff --git a/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php b/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php index efaeb5b8c508..2578ca748d0e 100644 --- a/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php +++ b/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php @@ -35,6 +35,7 @@ namespace Google\ApiCore\Transport\Grpc; use Grpc\ServerStreamingCall; +use stdClass; /** * Class ForwardingServerStreamingCall wraps a \Grpc\ServerStreamingCall. @@ -49,7 +50,7 @@ class ForwardingServerStreamingCall extends ForwardingCall /** * @return mixed An iterator of response values */ - public function responses() + public function responses(): mixed { return $this->innerCall->responses(); } @@ -57,10 +58,10 @@ public function responses() /** * Wait for the server to send the status, and return it. * - * @return \stdClass The status object, with integer $code, string + * @return ?stdClass The status object, with integer $code, string * $details, and array $metadata members */ - public function getStatus() + public function getStatus(): ?stdClass { return $this->innerCall->getStatus(); } diff --git a/Gax/src/Transport/Grpc/ForwardingUnaryCall.php b/Gax/src/Transport/Grpc/ForwardingUnaryCall.php index eb1c95116e15..5126c7c8c1a3 100644 --- a/Gax/src/Transport/Grpc/ForwardingUnaryCall.php +++ b/Gax/src/Transport/Grpc/ForwardingUnaryCall.php @@ -49,9 +49,9 @@ class ForwardingUnaryCall extends ForwardingCall /** * Wait for the server to respond with data and a status. * - * @return array [response data, status] + * @return ?array [response data, status] */ - public function wait() + public function wait(): ?array { return $this->innerCall->wait(); } diff --git a/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php b/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php index 38ab17f21f2c..99b6a4099391 100644 --- a/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php +++ b/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php @@ -34,8 +34,10 @@ namespace Google\ApiCore\Transport\Grpc; +use Generator; use Google\ApiCore\ServerStreamingCallInterface; use Grpc\ServerStreamingCall; +use stdClass; /** * Class ServerStreamingCallWrapper implements \Google\ApiCore\ServerStreamingCallInterface. @@ -53,7 +55,7 @@ public function __construct(ServerStreamingCall $stream) /** * {@inheritdoc} */ - public function start($data, array $metadata = [], array $callOptions = []) + public function start(mixed $data, array $metadata = [], array $callOptions = []): void { $this->stream->start($data, $metadata, $callOptions); } @@ -61,7 +63,7 @@ public function start($data, array $metadata = [], array $callOptions = []) /** * {@inheritdoc} */ - public function responses() + public function responses(): Generator { foreach ($this->stream->responses() as $response) { yield $response; @@ -71,7 +73,7 @@ public function responses() /** * {@inheritdoc} */ - public function getStatus() + public function getStatus(): ?stdClass { return $this->stream->getStatus(); } @@ -79,7 +81,7 @@ public function getStatus() /** * {@inheritdoc} */ - public function getMetadata() + public function getMetadata(): mixed { return $this->stream->getMetadata(); } @@ -87,7 +89,7 @@ public function getMetadata() /** * {@inheritdoc} */ - public function getTrailingMetadata() + public function getTrailingMetadata(): mixed { return $this->stream->getTrailingMetadata(); } @@ -95,7 +97,7 @@ public function getTrailingMetadata() /** * {@inheritdoc} */ - public function getPeer() + public function getPeer(): ?string { return $this->stream->getPeer(); } @@ -103,7 +105,7 @@ public function getPeer() /** * {@inheritdoc} */ - public function cancel() + public function cancel(): void { $this->stream->cancel(); } @@ -111,7 +113,7 @@ public function cancel() /** * {@inheritdoc} */ - public function setCallCredentials($call_credentials) + public function setCallCredentials(mixed $call_credentials): void { $this->stream->setCallCredentials($call_credentials); } diff --git a/Gax/src/Transport/GrpcFallbackTransport.php b/Gax/src/Transport/GrpcFallbackTransport.php index 66c27419f9c5..8008b6edd237 100644 --- a/Gax/src/Transport/GrpcFallbackTransport.php +++ b/Gax/src/Transport/GrpcFallbackTransport.php @@ -42,6 +42,7 @@ use Google\Protobuf\Internal\Message; use Google\Rpc\Status; use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Psr7\Request; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -84,7 +85,7 @@ public function __construct( * @return GrpcFallbackTransport * @throws ValidationException */ - public static function build(string $apiEndpoint, array $config = []) + public static function build(string $apiEndpoint, array $config = []): GrpcFallbackTransport { $config += [ 'httpHandler' => null, @@ -102,8 +103,18 @@ public static function build(string $apiEndpoint, array $config = []) /** * {@inheritdoc} + * @return never + * @throws \BadMethodCallException */ - public function startUnaryCall(Call $call, array $options) + public function startServerStreamingCall(Call $call, array $options): never + { + $this->throwUnsupportedException(); + } + + /** + * {@inheritdoc} + */ + public function startUnaryCall(Call $call, array $options): PromiseInterface { $httpHandler = $this->httpHandler; @@ -135,7 +146,7 @@ function (\Exception $ex) { * @param array $options * @return RequestInterface */ - private function buildGrpcFallbackRequest(Call $call, array $options) + private function buildGrpcFallbackRequest(Call $call, array $options): RequestInterface { // Build common headers and set the content type to 'application/x-protobuf' $headers = ['Content-Type' => 'application/x-protobuf'] + self::buildCommonHeaders($options); @@ -161,7 +172,7 @@ private function buildGrpcFallbackRequest(Call $call, array $options) * @param ResponseInterface $response * @return Message */ - private function unpackResponse(Call $call, ResponseInterface $response) + private function unpackResponse(Call $call, ResponseInterface $response): Message { $decodeType = $call->getDecodeType(); /** @var Message $responseMessage */ @@ -174,7 +185,7 @@ private function unpackResponse(Call $call, ResponseInterface $response) * @param array $options * @return array */ - private function getCallOptions(array $options) + private function getCallOptions(array $options): array { $callOptions = $options['transportOptions']['grpcFallbackOptions'] ?? []; @@ -203,7 +214,7 @@ private function getCallOptions(array $options) * @param \Exception $ex * @return \Exception */ - private function transformException(\Exception $ex) + private function transformException(\Exception $ex): \Exception { // Guzzle 7 carries the response on RequestException, Guzzle 8 only on // its ResponseException subclass, hence the method_exists() check. diff --git a/Gax/src/Transport/GrpcTransport.php b/Gax/src/Transport/GrpcTransport.php index d9d46cd4796f..de031f7d16e5 100644 --- a/Gax/src/Transport/GrpcTransport.php +++ b/Gax/src/Transport/GrpcTransport.php @@ -53,6 +53,7 @@ use Grpc\ChannelCredentials; use Grpc\Interceptor; use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\PromiseInterface; use Psr\Log\LoggerInterface; /** @@ -94,7 +95,7 @@ public function __construct( } parent::__construct($hostname, $opts, $channel); - $this->logger = $logger; + $this->logger = $logger ?: null; } /** @@ -116,7 +117,7 @@ public function __construct( * @return GrpcTransport * @throws ValidationException */ - public static function build(string $apiEndpoint, array $config = []) + public static function build(string $apiEndpoint, array $config = []): GrpcTransport { self::validateGrpcSupport(); $config += [ @@ -163,7 +164,7 @@ public static function build(string $apiEndpoint, array $config = []) /** * {@inheritdoc} */ - public function startBidiStreamingCall(Call $call, array $options) + public function startBidiStreamingCall(Call $call, array $options): BidiStream { $this->verifyUniverseDomain($options); @@ -198,7 +199,7 @@ public function startBidiStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function startClientStreamingCall(Call $call, array $options) + public function startClientStreamingCall(Call $call, array $options): ClientStream { $this->verifyUniverseDomain($options); @@ -218,7 +219,7 @@ public function startClientStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function startServerStreamingCall(Call $call, array $options) + public function startServerStreamingCall(Call $call, array $options): ServerStream { $this->verifyUniverseDomain($options); @@ -264,7 +265,7 @@ public function startServerStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function startUnaryCall(Call $call, array $options) + public function startUnaryCall(Call $call, array $options): PromiseInterface { $this->verifyUniverseDomain($options); $headers = $options['headers'] ?? []; @@ -326,14 +327,22 @@ function () use ($unaryCall, $options, &$promise, $requestEvent) { return $promise; } - private function verifyUniverseDomain(array $options) + /** + * {@inheritdoc} + */ + public function close(): void + { + parent::close(); + } + + private function verifyUniverseDomain(array $options): void { if (isset($options['credentialsWrapper'])) { $options['credentialsWrapper']->checkUniverseDomain(); } } - private function getCallOptions(array $options) + private function getCallOptions(array $options): array { $callOptions = $options['transportOptions']['grpcOptions'] ?? []; @@ -356,7 +365,7 @@ private function getGrpcUrl(): string return 'grpc://' . str_replace('dns:///', '', $this->getTarget()); } - private static function loadClientCertSource(callable $clientCertSource) + private static function loadClientCertSource(callable $clientCertSource): array { return call_user_func($clientCertSource); } diff --git a/Gax/src/Transport/HttpUnaryTransportTrait.php b/Gax/src/Transport/HttpUnaryTransportTrait.php index 8a9b3bea16b7..bde22e98091f 100644 --- a/Gax/src/Transport/HttpUnaryTransportTrait.php +++ b/Gax/src/Transport/HttpUnaryTransportTrait.php @@ -47,16 +47,18 @@ */ trait HttpUnaryTransportTrait { + /** @var callable */ private $httpHandler; - private $transportName; - private $clientCertSource; + private string $transportName; + /** @var callable|null */ + private $clientCertSource = null; /** * {@inheritdoc} * @return never * @throws \BadMethodCallException */ - public function startClientStreamingCall(Call $call, array $options) + public function startClientStreamingCall(Call $call, array $options): never { $this->throwUnsupportedException(); } @@ -66,17 +68,7 @@ public function startClientStreamingCall(Call $call, array $options) * @return never * @throws \BadMethodCallException */ - public function startServerStreamingCall(Call $call, array $options) - { - $this->throwUnsupportedException(); - } - - /** - * {@inheritdoc} - * @return never - * @throws \BadMethodCallException - */ - public function startBidiStreamingCall(Call $call, array $options) + public function startBidiStreamingCall(Call $call, array $options): never { $this->throwUnsupportedException(); } @@ -84,7 +76,7 @@ public function startBidiStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function close() + public function close(): void { // Nothing to do. } @@ -93,7 +85,7 @@ public function close() * @param array $options * @return array */ - private static function buildCommonHeaders(array $options) + private static function buildCommonHeaders(array $options): array { $headers = $options['headers'] ?? []; @@ -129,7 +121,7 @@ private static function buildCommonHeaders(array $options) * @return callable * @throws ValidationException */ - private static function buildHttpHandlerAsync(null|false|LoggerInterface $logger = null) + private static function buildHttpHandlerAsync(null|false|LoggerInterface $logger = null): callable { try { return [HttpHandlerFactory::build(logger: $logger), 'async']; @@ -143,7 +135,7 @@ private static function buildHttpHandlerAsync(null|false|LoggerInterface $logger * * @param callable $clientCertSource */ - private function configureMtlsChannel(callable $clientCertSource) + private function configureMtlsChannel(callable $clientCertSource): void { $this->clientCertSource = $clientCertSource; } @@ -152,14 +144,14 @@ private function configureMtlsChannel(callable $clientCertSource) * @return never * @throws \BadMethodCallException */ - private function throwUnsupportedException() + private function throwUnsupportedException(): never { throw new \BadMethodCallException( "Streaming calls are not supported while using the {$this->transportName} transport." ); } - private static function loadClientCertSource(callable $clientCertSource) + private static function loadClientCertSource(callable $clientCertSource): array { $certFile = tempnam(sys_get_temp_dir(), 'cert'); $keyFile = tempnam(sys_get_temp_dir(), 'key'); diff --git a/Gax/src/Transport/Rest/JsonStreamDecoder.php b/Gax/src/Transport/Rest/JsonStreamDecoder.php index d0366fc435e6..d0c186294af2 100644 --- a/Gax/src/Transport/Rest/JsonStreamDecoder.php +++ b/Gax/src/Transport/Rest/JsonStreamDecoder.php @@ -34,6 +34,7 @@ namespace Google\ApiCore\Transport\Rest; +use Generator; use Psr\Http\Message\StreamInterface; use RuntimeException; @@ -89,9 +90,9 @@ public function __construct(StreamInterface $stream, string $decodeType, array $ * byte is read or if it encounters an error while decoding a message. * * @throws RuntimeException - * @return \Generator + * @return Generator */ - public function decode() + public function decode(): Generator { try { foreach ($this->doDecode() as $response) { @@ -112,9 +113,9 @@ public function decode() } /** - * @return \Generator + * @return Generator */ - private function doDecode() + private function doDecode(): Generator { $decodeType = $this->decodeType; $str = false; @@ -232,7 +233,7 @@ private function doDecode() * * @return void */ - public function close() + public function close(): void { $this->closeCalled = true; $this->stream->close(); diff --git a/Gax/src/Transport/Rest/RestServerStreamingCall.php b/Gax/src/Transport/Rest/RestServerStreamingCall.php index 5544ff2a0dc3..b92cdb5ed45f 100644 --- a/Gax/src/Transport/Rest/RestServerStreamingCall.php +++ b/Gax/src/Transport/Rest/RestServerStreamingCall.php @@ -34,6 +34,7 @@ namespace Google\ApiCore\Transport\Rest; +use Generator; use Google\ApiCore\ApiException; use Google\ApiCore\ApiStatus; use Google\ApiCore\ServerStreamingCallInterface; @@ -59,8 +60,8 @@ class RestServerStreamingCall implements ServerStreamingCallInterface private RequestInterface $originalRequest; private JsonStreamDecoder $decoder; private string $decodeType; - private ?ResponseInterface $response; - private stdClass $status; + private ?ResponseInterface $response = null; + private ?stdClass $status = null; /** * @param callable $httpHandler @@ -77,7 +78,7 @@ public function __construct(callable $httpHandler, string $decodeType, array $de /** * {@inheritdoc} */ - public function start($request, array $headers = [], array $callOptions = []) + public function start(mixed $request, array $headers = [], array $callOptions = []): void { $this->originalRequest = $this->appendHeaders($request, $headers); @@ -111,7 +112,7 @@ public function start($request, array $headers = [], array $callOptions = []) * @param array $headers * @return RequestInterface */ - private function appendHeaders(RequestInterface $request, array $headers) + private function appendHeaders(RequestInterface $request, array $headers): RequestInterface { foreach ($headers as $key => $value) { $request = $request->hasHeader($key) ? @@ -125,7 +126,7 @@ private function appendHeaders(RequestInterface $request, array $headers) /** * {@inheritdoc} */ - public function responses() + public function responses(): Generator { if (is_null($this->response)) { throw new \Exception('Stream has not been started.'); @@ -147,10 +148,10 @@ public function responses() * Return the status of the server stream. If the call has not been started * this will be null. * - * @return stdClass The status, with integer $code, string + * @return ?stdClass The status, with integer $code, string * $details, and array $metadata members */ - public function getStatus() + public function getStatus(): ?stdClass { return $this->status; } @@ -158,7 +159,7 @@ public function getStatus() /** * {@inheritdoc} */ - public function getMetadata() + public function getMetadata(): ?array { return is_null($this->response) ? null : $this->response->getHeaders(); } @@ -167,7 +168,7 @@ public function getMetadata() * The Rest transport does not support trailing metadata. This is a * passthrough to getMetadata(). */ - public function getTrailingMetadata() + public function getTrailingMetadata(): ?array { return $this->getMetadata(); } @@ -175,7 +176,7 @@ public function getTrailingMetadata() /** * {@inheritdoc} */ - public function getPeer() + public function getPeer(): string { return (string) $this->originalRequest->getUri(); } @@ -183,7 +184,7 @@ public function getPeer() /** * {@inheritdoc} */ - public function cancel() + public function cancel(): void { if (isset($this->decoder)) { $this->decoder->close(); @@ -194,7 +195,7 @@ public function cancel() * For the REST transport this is a no-op. * {@inheritdoc} */ - public function setCallCredentials($call_credentials) + public function setCallCredentials(mixed $call_credentials): void { // Do nothing. } diff --git a/Gax/src/Transport/RestTransport.php b/Gax/src/Transport/RestTransport.php index eb01d16d4a39..31397e2d8a05 100644 --- a/Gax/src/Transport/RestTransport.php +++ b/Gax/src/Transport/RestTransport.php @@ -45,6 +45,7 @@ use Google\ApiCore\ValidationTrait; use Google\Protobuf\Internal\Message; use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Promise\PromiseInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -55,9 +56,7 @@ class RestTransport implements TransportInterface, ResumableUploadTransportInter { use ApiEndpointTrait; use ValidationTrait; - use HttpUnaryTransportTrait { - startServerStreamingCall as protected unsupportedServerStreamingCall; - } + use HttpUnaryTransportTrait; private RequestBuilder $requestBuilder; @@ -92,7 +91,7 @@ public function __construct( * @return RestTransport * @throws ValidationException */ - public static function build(string $apiEndpoint, string $restConfigPath, array $config = []) + public static function build(string $apiEndpoint, string $restConfigPath, array $config = []): RestTransport { $config += [ 'httpHandler' => null, @@ -115,7 +114,7 @@ public static function build(string $apiEndpoint, string $restConfigPath, array /** * {@inheritdoc} */ - public function startUnaryCall(Call $call, array $options) + public function startUnaryCall(Call $call, array $options): PromiseInterface { $headers = self::buildCommonHeaders($options); @@ -188,7 +187,7 @@ function (\Throwable $ex) { * {@inheritdoc} * @throws \BadMethodCallException for forwards compatibility with older GAPIC clients */ - public function startServerStreamingCall(Call $call, array $options) + public function startServerStreamingCall(Call $call, array $options): ServerStream { $message = $call->getMessage(); if (!$message) { @@ -198,7 +197,7 @@ public function startServerStreamingCall(Call $call, array $options) // Maintain forwards compatibility with older GAPIC clients not configured for REST server streaming // @see https://github.com/googleapis/gax-php/issues/370 if (!$this->requestBuilder->pathExists($call->getMethod())) { - $this->unsupportedServerStreamingCall($call, $options); + $this->throwUnsupportedException(); } $headers = self::buildCommonHeaders($options); @@ -232,9 +231,9 @@ public function startServerStreamingCall(Call $call, array $options) * * @param RequestInterface $request * @param array $options - * @return \Psr\Http\Message\ResponseInterface|\GuzzleHttp\Promise\PromiseInterface + * @return ResponseInterface|PromiseInterface */ - public function sendRawRequest(RequestInterface $request, array $options = []) + public function sendRawRequest(RequestInterface $request, array $options = []): ResponseInterface|PromiseInterface { return ($this->httpHandler)($request, $options); } @@ -265,13 +264,13 @@ public function buildRequest(string $method, ?Message $message = null, array $he * @return RestServerStreamingCall */ private function doServerStreamRequest( - $httpHandler, - $request, - $headers, - $decodeType, - $callOptions, - $decoderOptions = [] - ) { + callable $httpHandler, + RequestInterface $request, + array $headers, + string $decodeType, + array $callOptions, + array $decoderOptions = [] + ): RestServerStreamingCall { $call = new RestServerStreamingCall( $httpHandler, $decodeType, @@ -287,7 +286,7 @@ private function doServerStreamRequest( * * @return array */ - private function getCallOptions(array $options) + private function getCallOptions(array $options): array { $callOptions = $options['transportOptions']['restOptions'] ?? []; diff --git a/Gax/src/Transport/TransportInterface.php b/Gax/src/Transport/TransportInterface.php index 8ae6d918c590..9aaca0a147ed 100644 --- a/Gax/src/Transport/TransportInterface.php +++ b/Gax/src/Transport/TransportInterface.php @@ -51,7 +51,7 @@ interface TransportInterface * * @return BidiStream */ - public function startBidiStreamingCall(Call $call, array $options); + public function startBidiStreamingCall(Call $call, array $options): BidiStream; /** * Starts a client streaming call. @@ -61,7 +61,7 @@ public function startBidiStreamingCall(Call $call, array $options); * * @return ClientStream */ - public function startClientStreamingCall(Call $call, array $options); + public function startClientStreamingCall(Call $call, array $options): ClientStream; /** * Starts a server streaming call. @@ -71,7 +71,7 @@ public function startClientStreamingCall(Call $call, array $options); * * @return ServerStream */ - public function startServerStreamingCall(Call $call, array $options); + public function startServerStreamingCall(Call $call, array $options): ServerStream; /** * Returns a promise used to execute network requests. @@ -82,12 +82,12 @@ public function startServerStreamingCall(Call $call, array $options); * @return PromiseInterface * @throws ValidationException */ - public function startUnaryCall(Call $call, array $options); + public function startUnaryCall(Call $call, array $options): PromiseInterface; /** * Closes the connection, if one exists. * * @return void */ - public function close(); + public function close(): void; } diff --git a/Gax/tests/Unit/ClientOptionsTraitTest.php b/Gax/tests/Unit/ClientOptionsTraitTest.php index 8adb06babe81..2740ba2b37cd 100644 --- a/Gax/tests/Unit/ClientOptionsTraitTest.php +++ b/Gax/tests/Unit/ClientOptionsTraitTest.php @@ -146,10 +146,15 @@ public function testCreateCredentialsWrapper($auth, $authConfig, $expectedCreden public function createCredentialsWrapperData() { + $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; + $keyFile = json_decode(file_get_contents($keyFilePath), true); + $fetcher = $this->prophesize(FetchAuthTokenInterface::class)->reveal(); $credentialsWrapper = new CredentialsWrapper($fetcher); return [ + [$keyFilePath, [], CredentialsWrapper::build(['keyFile' => $keyFile])], + [$keyFile, [], CredentialsWrapper::build(['keyFile' => $keyFile])], [$fetcher, [], new CredentialsWrapper($fetcher)], [$credentialsWrapper, [], $credentialsWrapper], ]; @@ -173,6 +178,28 @@ public function testCreateCredentialsWrapperFromEnv() $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper); } + public function testCreateCredentialsWrapperValidationException() + { + $this->expectException(ValidationException::class); + + $this->clientStub->createCredentialsWrapper( + 'not a json string', + [], + '' + ); + } + + public function testCreateCredentialsWrapperInvalidArgumentException() + { + $this->expectException(\InvalidArgumentException::class); + + $this->clientStub->createCredentialsWrapper( + ['array' => 'without right keys'], + [], + '' + ); + } + /** * @dataProvider buildClientOptionsProvider */ diff --git a/Gax/tests/Unit/CredentialsWrapperTest.php b/Gax/tests/Unit/CredentialsWrapperTest.php index 45c260e7e9f8..5e26985963c1 100644 --- a/Gax/tests/Unit/CredentialsWrapperTest.php +++ b/Gax/tests/Unit/CredentialsWrapperTest.php @@ -39,6 +39,7 @@ use Google\Auth\Cache\SysVCacheItemPool; use Google\Auth\Credentials\GCECredentials; use Google\Auth\Credentials\ServiceAccountCredentials; +use Google\Auth\CredentialsLoader; use Google\Auth\FetchAuthTokenCache; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GCECache; @@ -68,6 +69,15 @@ public function testBuildWithoutExplicitKeyFile($args, $expectedCredentialsWrapp $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', $appDefaultCreds); } + /** + * @dataProvider buildDataWithKeyFile + */ + public function testBuildWithKeyFile($args, $expectedCredentialsWrapper) + { + $actualCredentialsWrapper = CredentialsWrapper::build($args); + $this->assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper); + } + public function buildDataWithoutExplicitKeyFile() { $appDefaultCreds = getenv('GOOGLE_APPLICATION_CREDENTIALS'); @@ -170,6 +180,69 @@ public function buildDataWithoutExplicitKeyFile() return $testData; } + public function buildDataWithKeyFile() + { + $keyFilePath = __DIR__ . '/testdata/creds/json-key-file.json'; + $keyFile = json_decode(file_get_contents($keyFilePath), true); + + $scopes = ['myscope']; + $authHttpHandler = function () { + }; + $defaultAuthCache = new MemoryCacheItemPool(); + $authCache = new SysVCacheItemPool(); + $authCacheOptions = ['lifetime' => 600]; + $quotaProject = 'my-quota-project'; + return [ + [ + ['keyFile' => $keyFile], + $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null), + ], + [ + ['keyFile' => $keyFilePath], + $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, null, null), + ], + [ + ['keyFile' => $keyFile, 'scopes' => $scopes], + $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, null), + ], + [ + ['keyFile' => $keyFile, 'scopes' => $scopes, 'authHttpHandler' => $authHttpHandler], + $this->makeExpectedKeyFileCreds($keyFile, $scopes, $defaultAuthCache, null, $authHttpHandler), + ], + [ + ['keyFile' => $keyFile, 'enableCaching' => false], + $this->makeExpectedKeyFileCreds($keyFile, null, null, null, null), + ], + [ + ['keyFile' => $keyFile, 'authCacheOptions' => $authCacheOptions], + $this->makeExpectedKeyFileCreds($keyFile, null, $defaultAuthCache, $authCacheOptions, null), + ], + [ + ['keyFile' => $keyFile, 'authCache' => $authCache], + $this->makeExpectedKeyFileCreds($keyFile, null, $authCache, null, null), + ], + [ + ['keyFile' => $keyFile, 'quotaProject' => $quotaProject], + $this->makeExpectedKeyFileCreds( + $keyFile + ['quota_project_id' => $quotaProject], + null, + $defaultAuthCache, + null, + null + ), + ], + ]; + } + + private function makeExpectedKeyFileCreds($keyFile, $scopes, $cache, $cacheConfig, $httpHandler) + { + $loader = CredentialsLoader::makeCredentials($scopes, $keyFile); + if ($cache) { + $loader = new FetchAuthTokenCache($loader, $cacheConfig, $cache); + } + return new CredentialsWrapper($loader, $httpHandler); + } + /** * @dataProvider provideCheckUniverseDomainFails */ diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 2ee00cbdb0b0..17ef0f4c2986 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -964,7 +964,7 @@ public function testBuildClientOptionsRegionalEndpoint(?string $apiEndpoint, ?st public array $capturedCredentialsConfig = []; public function createCredentialsWrapper( - FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, array $credentialsConfig, string $universeDomain ): HeaderCredentialsInterface { @@ -1080,6 +1080,31 @@ public function buildRequestHeaderParams() ]; } + public function testServiceAddressOption() + { + $client = new StubGapicClient(); + $apiEndpoint = 'test.address.com:443'; + $updatedOptions = $client->buildClientOptions( + ['serviceAddress' => $apiEndpoint] + ); + $client->setClientOptions($updatedOptions); + + $this->assertEquals($apiEndpoint, $updatedOptions['apiEndpoint']); + $this->assertArrayNotHasKey('serviceAddress', $updatedOptions); + } + + public function testModifyClientOptions() + { + $options = []; + $client = new StubGapicClientExtension(); + $updatedOptions = $client->buildClientOptions($options); + $client->setClientOptions($updatedOptions); + + $this->assertArrayHasKey('addNewOption', $updatedOptions); + $this->assertTrue($updatedOptions['disableRetries']); + $this->assertEquals('abc123', $updatedOptions['apiEndpoint']); + } + private function buildClientToTestModifyCallMethods($clientClass = null) { $header = AgentHeader::buildAgentHeader([]); @@ -1520,7 +1545,7 @@ public function __construct( $this->handler = $handler; $this->m1Called = &$m1Called; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->m1Called = true; return ($this->handler)($call, $options); @@ -1538,7 +1563,7 @@ public function __construct( $this->handler = $handler; $this->m2Called = &$m2Called; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->m2Called = true; return ($this->handler)($call, $options); @@ -1591,7 +1616,7 @@ public function __construct( $this->handler = $handler; $this->callOrder = &$callOrder; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->callOrder[] = 'middleware1'; return ($this->handler)($call, $options); @@ -1609,7 +1634,7 @@ public function __construct( $this->handler = $handler; $this->callOrder = &$callOrder; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->callOrder[] = 'middleware2'; return ($this->handler)($call, $options); @@ -1661,7 +1686,7 @@ public function __construct( $this->handler = $handler; $this->callOrder = &$callOrder; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->callOrder[] = 'middleware1'; return ($this->handler)($call, $options); @@ -1679,7 +1704,7 @@ public function __construct( $this->handler = $handler; $this->callOrder = &$callOrder; } - public function __invoke(Call $call, array $options) + public function __invoke(Call $call, array $options): PromiseInterface { $this->callOrder[] = 'middleware2'; return ($this->handler)($call, $options); @@ -2004,6 +2029,13 @@ public function get($name) class StubGapicClientExtension extends StubGapicClient { + protected function modifyClientOptions(array &$options) + { + $options['disableRetries'] = true; + $options['addNewOption'] = true; + $options['apiEndpoint'] = 'abc123'; + } + protected function modifyUnaryCallable(callable &$callable) { $originalCallable = $callable; diff --git a/Gax/tests/Unit/Middleware/FixedHeaderMiddlewareTest.php b/Gax/tests/Unit/Middleware/FixedHeaderMiddlewareTest.php index b11252a510db..46bfc064d1f2 100644 --- a/Gax/tests/Unit/Middleware/FixedHeaderMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/FixedHeaderMiddlewareTest.php @@ -34,6 +34,7 @@ use Google\ApiCore\Call; use Google\ApiCore\Middleware\FixedHeaderMiddleware; +use GuzzleHttp\Promise\PromiseInterface; use PHPUnit\Framework\TestCase; use Prophecy\PhpUnit\ProphecyTrait; @@ -51,6 +52,7 @@ public function testCustomHeader() $callable = function (Call $call, $options) use ($fixedHeader, &$handlerCalled) { $this->assertEquals($fixedHeader, $options['headers']); $handlerCalled = true; + return $this->createMock(PromiseInterface::class); }; $middleware = new FixedHeaderMiddleware($callable, $fixedHeader); $middleware($call->reveal(), []); @@ -77,6 +79,7 @@ public function testCustomHeaderNoOverride() $callable = function (Call $call, $options) use ($expectedHeader, &$handlerCalled) { $this->assertEquals($expectedHeader, $options['headers']); $handlerCalled = true; + return $this->createMock(PromiseInterface::class); }; $middleware = new FixedHeaderMiddleware($callable, $fixedHeader); $middleware($call->reveal(), ['headers' => $userHeader]); @@ -104,6 +107,7 @@ public function testCustomHeaderOverride() $callable = function (Call $call, $options) use ($expectedHeader, &$handlerCalled) { $this->assertEquals($expectedHeader, $options['headers']); $handlerCalled = true; + return $this->createMock(PromiseInterface::class); }; $middleware = new FixedHeaderMiddleware($callable, $fixedHeader, true); $middleware($call->reveal(), ['headers' => $userHeader]); diff --git a/Gax/tests/Unit/Middleware/RequestAutoPopulationMiddlewareTest.php b/Gax/tests/Unit/Middleware/RequestAutoPopulationMiddlewareTest.php index 624ae9bfd036..072355488d51 100644 --- a/Gax/tests/Unit/Middleware/RequestAutoPopulationMiddlewareTest.php +++ b/Gax/tests/Unit/Middleware/RequestAutoPopulationMiddlewareTest.php @@ -36,6 +36,7 @@ use Google\ApiCore\Call; use Google\ApiCore\Middleware\RequestAutoPopulationMiddleware; use Google\ApiCore\Testing\MockRequest; +use GuzzleHttp\Promise\PromiseInterface; use PHPUnit\Framework\TestCase; use Ramsey\Uuid\Uuid; @@ -44,16 +45,17 @@ class RequestAutoPopulationMiddlewareTest extends TestCase public function testRequestPopulated() { $request = new MockRequest(); - $next = function ($call, $options) { + $expectedPromise = $this->createMock(PromiseInterface::class); + $next = function ($call, $options) use ($expectedPromise) { $this->assertTrue(Uuid::isValid($call->getMessage()->getPageToken())); - return true; + return $expectedPromise; }; $call = new Call('GetExample', 'Example', $request); $middleware = new RequestAutoPopulationMiddleware( $next, ['pageToken' => Format::UUID4] ); - $this->assertTrue($middleware->__invoke($call, [])); + $this->assertSame($expectedPromise, $middleware->__invoke($call, [])); } public function testRequestAutoPopulatedThrowsForInvalidValueType() @@ -66,7 +68,7 @@ public function testRequestAutoPopulatedThrowsForInvalidValueType() $request = new MockRequest(); $next = function ($call, $options) { $this->assertTrue(empty($call->getMessage()->getPageToken())); - return true; + return $this->createMock(PromiseInterface::class); }; $call = new Call('GetExample', 'Example', $request); $middleware = new RequestAutoPopulationMiddleware( diff --git a/Gax/tests/Unit/PathTemplateTest.php b/Gax/tests/Unit/PathTemplateTest.php index f994374e4fea..5621534909a5 100644 --- a/Gax/tests/Unit/PathTemplateTest.php +++ b/Gax/tests/Unit/PathTemplateTest.php @@ -99,14 +99,6 @@ public function testFailUnexpectedEof() new PathTemplate('a/{hello=world'); } - public function testFailNullString() - { - $this->expectException(ValidationException::class); - $this->expectExceptionMessage('Cannot construct PathTemplate from empty string'); - - new PathTemplate(null); - } - public function testFailEmptyString() { $this->expectException(ValidationException::class); diff --git a/Gax/tests/Unit/ResumableUpload/ResumableUploadClientTest.php b/Gax/tests/Unit/ResumableUpload/ResumableUploadClientTest.php index 6deb9f4be7b7..abb1ea5875ec 100644 --- a/Gax/tests/Unit/ResumableUpload/ResumableUploadClientTest.php +++ b/Gax/tests/Unit/ResumableUpload/ResumableUploadClientTest.php @@ -41,11 +41,13 @@ use Google\ApiCore\RetrySettings; use Google\Protobuf\Internal\Message; use Google\Protobuf\Timestamp; +use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Psr7\Utils; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; class ResumableUploadClientTest extends TestCase @@ -58,8 +60,10 @@ private function createStubTransport($requestBuilder, $httpHandler): ResumableUp public function __construct(private $requestBuilder, private $httpHandler) { } - public function sendRawRequest(RequestInterface $request, array $options = []) - { + public function sendRawRequest( + RequestInterface $request, + array $options = [] + ): ResponseInterface|PromiseInterface { return ($this->httpHandler)($request, $options); } public function buildRequest( diff --git a/Gax/tests/Unit/ResumableUpload/ResumableUploadTest.php b/Gax/tests/Unit/ResumableUpload/ResumableUploadTest.php index 8bc057d4ef9f..48d57326e219 100644 --- a/Gax/tests/Unit/ResumableUpload/ResumableUploadTest.php +++ b/Gax/tests/Unit/ResumableUpload/ResumableUploadTest.php @@ -40,12 +40,14 @@ use Google\Protobuf\Internal\Message; use Google\Protobuf\Timestamp; use GuzzleHttp\Promise\Create; +use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\PhpUnit\ProphecyTrait; use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; class ResumableUploadTest extends TestCase { @@ -57,8 +59,10 @@ private function createStubTransport($requestBuilder, $httpHandler): ResumableUp public function __construct(private $requestBuilder, private $httpHandler) { } - public function sendRawRequest(RequestInterface $request, array $options = []) - { + public function sendRawRequest( + RequestInterface $request, + array $options = [] + ): ResponseInterface|PromiseInterface { return ($this->httpHandler)($request, $options); } public function buildRequest( diff --git a/Logging/tests/Unit/Connection/GapicTest.php b/Logging/tests/Unit/Connection/GapicTest.php index 35265bc3a8ee..dbe501401944 100644 --- a/Logging/tests/Unit/Connection/GapicTest.php +++ b/Logging/tests/Unit/Connection/GapicTest.php @@ -17,7 +17,7 @@ namespace Google\Cloud\Logging\Tests\Unit\Connection; -use Google\ApiCore\GPBType; +use Google\Protobuf\Internal\GPBType; use Google\ApiCore\Page; use Google\ApiCore\PagedListResponse; use Google\Cloud\Logging\Connection\Grpc; diff --git a/PubSub/tests/Unit/BatchPublisherTest.php b/PubSub/tests/Unit/BatchPublisherTest.php index a0c503233021..5b42724110e8 100644 --- a/PubSub/tests/Unit/BatchPublisherTest.php +++ b/PubSub/tests/Unit/BatchPublisherTest.php @@ -17,9 +17,9 @@ namespace Google\Cloud\PubSub\Tests\Unit; -use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Core\Batch\BatchRunner; use Google\Cloud\Core\RequestHandler; +use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\BatchPublisher; use Google\Cloud\PubSub\Connection\ConnectionInterface; @@ -91,7 +91,7 @@ public function testPublishDeferred() [ 'suppressKeyFileNotice' => true, 'projectId' => 'example-project', - 'credentials' => new InsecureCredentialsWrapper() + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() ] ], [ 'encode', 'requestHandler' @@ -166,7 +166,7 @@ public function testPublisherCompression( [ 'suppressKeyFileNotice' => true, 'projectId' => 'example-project', - 'credentials' => new InsecureCredentialsWrapper() + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() ] ], [ 'encode', 'requestHandler' diff --git a/PubSub/tests/Unit/PubSubClientTest.php b/PubSub/tests/Unit/PubSubClientTest.php index 63dfc007fda7..b7340103cd41 100644 --- a/PubSub/tests/Unit/PubSubClientTest.php +++ b/PubSub/tests/Unit/PubSubClientTest.php @@ -17,13 +17,13 @@ namespace Google\Cloud\PubSub\Tests\Unit; -use Google\ApiCore\InsecureCredentialsWrapper; use Google\Cloud\Core\Duration; use Google\Cloud\Core\Exception\BadRequestException; use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\RequestHandler; use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Core\Timestamp; use Google\Cloud\PubSub\Message; use Google\Cloud\PubSub\PubSubClient; @@ -63,7 +63,7 @@ public function setUp(): void [ 'projectId' => self::PROJECT, 'transport' => 'rest', - 'credentials' => new InsecureCredentialsWrapper() + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() ] ], ['requestHandler']); } diff --git a/Spanner/src/Middleware/MetricsAttemptMiddleware.php b/Spanner/src/Middleware/MetricsAttemptMiddleware.php index 7105f74cb38a..7ba804e31503 100644 --- a/Spanner/src/Middleware/MetricsAttemptMiddleware.php +++ b/Spanner/src/Middleware/MetricsAttemptMiddleware.php @@ -34,7 +34,9 @@ use Exception; use Google\ApiCore\ApiException; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\ServerStream; use Google\Cloud\Spanner\OpenTelemetry\MetricsContext; @@ -133,8 +135,10 @@ public function __construct( ); } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $next = $this->nextHandler; $startTime = microtime(true); diff --git a/Spanner/src/Middleware/MetricsOperationMiddleware.php b/Spanner/src/Middleware/MetricsOperationMiddleware.php index dd200b7cb0a3..626afd20dbcd 100644 --- a/Spanner/src/Middleware/MetricsOperationMiddleware.php +++ b/Spanner/src/Middleware/MetricsOperationMiddleware.php @@ -33,7 +33,9 @@ namespace Google\Cloud\Spanner\Middleware; use Exception; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; use Google\ApiCore\Middleware\MiddlewareInterface; use Google\ApiCore\ServerStream; use Google\Cloud\Spanner\OpenTelemetry\MetricsContext; @@ -103,8 +105,10 @@ public function __construct( ); } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $next = $this->nextHandler; /** @var MetricsContext|null $metricsContext */ diff --git a/Spanner/src/Middleware/RequestIdHeaderMiddleware.php b/Spanner/src/Middleware/RequestIdHeaderMiddleware.php index 34419c1134ee..2c9577a251f0 100644 --- a/Spanner/src/Middleware/RequestIdHeaderMiddleware.php +++ b/Spanner/src/Middleware/RequestIdHeaderMiddleware.php @@ -32,8 +32,12 @@ namespace Google\Cloud\Spanner\Middleware; +use Google\ApiCore\BidiStream; use Google\ApiCore\Call; +use Google\ApiCore\ClientStream; use Google\ApiCore\Middleware\MiddlewareInterface; +use Google\ApiCore\ServerStream; +use GuzzleHttp\Promise\PromiseInterface; /** * Middleware that adds the RequestId header to each rpc call made by spanner @@ -60,8 +64,10 @@ public function __construct(callable $nextHandler, int $channelId) $this->client = self::$currentClient++; } - public function __invoke(Call $call, array $options) - { + public function __invoke( + Call $call, + array $options + ): PromiseInterface|ClientStream|ServerStream|BidiStream { $options['headers'][self::REQUEST_ID_HEADER_NAME] = [$this->getNewHeaderValue($options)]; $next = $this->nextHandler; return $next( diff --git a/Spanner/src/SpannerClient.php b/Spanner/src/SpannerClient.php index 1bcdcea3c8a2..dcaddb2954ff 100644 --- a/Spanner/src/SpannerClient.php +++ b/Spanner/src/SpannerClient.php @@ -1064,7 +1064,7 @@ private function configureKeepAlive(array $config): array private function configureMetrics( array $options, - FetchAuthTokenInterface|HeaderCredentialsInterface|null $rawCredentials = null + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $rawCredentials = null ): void { $timeoutMillis = $this->pluck('metricsTimeoutMillis', $options, false) ?? 100; @@ -1188,7 +1188,7 @@ private function generateClientHash(string $clientUid): string } private function buildMetricsCredentials( - FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, array $options ): HeaderCredentialsInterface { $credentialsConfig = [ diff --git a/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php b/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php index 1a30f2fee841..ccae3109a533 100644 --- a/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php +++ b/Spanner/tests/Unit/RequestIdHeaderMiddlewareTest.php @@ -71,7 +71,7 @@ public function testAddsRequestIdHeader() $this->assertEquals(1, (int)$request, 'The request ID part of the header is incorrect.'); $this->assertEquals(1, (int)$attempt, 'The attempt ID part of the header is incorrect.'); - return 'foo'; + return new FulfilledPromise('foo'); }; $middleware = new RequestIdHeaderMiddleware($nextHandler, $channelId); @@ -90,7 +90,7 @@ public function testMaintainsProcessIdAcrossCalls() $parts = explode('.', $headerValue); $capturedProcesses[] = $parts[1]; // Capture the process ID - return 'ok'; + return new FulfilledPromise('ok'); }; $middleware = new RequestIdHeaderMiddleware($nextHandler, $channelId); @@ -130,7 +130,7 @@ public function testRequestPartIncrementsWithEachCall() $parts = explode('.', $headerValue); $capturedRequests[] = (int) $parts[4]; // Capture the request ID part - return 'ok'; + return new FulfilledPromise('ok'); }; $middleware = new RequestIdHeaderMiddleware($nextHandler, $channelId); @@ -161,7 +161,7 @@ public function testAttemptPartReflectsRetryAttempt() $this->assertCount(6, $parts, 'Header should have 6 parts.'); $this->assertEquals($retryAttempt + 1, (int)$parts[5], 'The attempt ID should be retryAttempt + 1.'); - return 'ok'; + return new FulfilledPromise('ok'); }; $middleware = new RequestIdHeaderMiddleware($nextHandler, $channelId); diff --git a/Spanner/tests/Unit/SpannerClientTest.php b/Spanner/tests/Unit/SpannerClientTest.php index 86457a80ed90..62e231cac99b 100644 --- a/Spanner/tests/Unit/SpannerClientTest.php +++ b/Spanner/tests/Unit/SpannerClientTest.php @@ -17,7 +17,6 @@ namespace Google\Cloud\Spanner\Tests\Unit; -use Google\ApiCore\InsecureCredentialsWrapper; use Google\ApiCore\OperationResponse; use Google\ApiCore\Page; use Google\ApiCore\PagedListResponse; @@ -26,6 +25,7 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\Snippet\Fixtures; use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\Instance as InstanceProto; @@ -109,7 +109,7 @@ public function setUp(): void ])); $this->spannerClient = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -555,7 +555,7 @@ public function testClientPassesIsolationLevel() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'isolationLevel' => IsolationLevel::REPEATABLE_READ, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), ]); $reflectedClient = new ReflectionClass($client); @@ -589,7 +589,7 @@ public function testTransactionHasCorrectIsolationLevel() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'isolationLevel' => IsolationLevel::REPEATABLE_READ, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), ]); $reflectedClient = new ReflectionClass($client); @@ -623,7 +623,7 @@ public function testClientPassesReadLockMode() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'readLockMode' => ReadLockMode::PESSIMISTIC, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), ]); $reflectedClient = new ReflectionClass($client); @@ -657,7 +657,7 @@ public function testTransactionHasCorrectReadLockMode() 'projectId' => self::PROJECT, 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'readLockMode' => ReadLockMode::PESSIMISTIC, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), ]); $reflectedClient = new ReflectionClass($client); @@ -694,7 +694,7 @@ public function testOptionsWithoutChannelIncreasesChannelId() /** @var SpannerClient $client */ $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -714,7 +714,7 @@ public function testOptionsWithChannelDoesNotIncreasesChannelId() $client = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -731,7 +731,7 @@ public function testOptionsWithChannelDoesNotIncreasesChannelId() $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -761,7 +761,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This client is using a shared channel. This has not been previously used, so this should increase the count. $client = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -777,7 +777,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This client is not using a shared channel, increasing the total once more to 3 channels. $client2 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -792,7 +792,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // This is using an entirely new Channel. This should increase the total channels to 4. $client3 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -809,7 +809,7 @@ public function testCreateMultipleInstancesWithAndWithoutChannels() // As this has been seen before, the total should not increase. $client4 = new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'directedReadOptions' => $this->directedReadOptionsIncludeReplicas, 'gapicSpannerClient' => $this->gapicSpannerClient->reveal(), 'gapicSpannerInstanceAdminClient' => $this->instanceAdminClient->reveal(), @@ -835,7 +835,7 @@ public function testConfigureKeepAlive() { $client = new SpannerClient([ 'projectId' => 'test-project', - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), ]); $reflection = new ReflectionClass($client); $method = $reflection->getMethod('configureKeepAlive'); @@ -880,7 +880,7 @@ public function testBuiltinMetricsDisabledByDefault() new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'gapicSpannerClient' => $gapicSpannerClient->reveal(), ]); } @@ -895,7 +895,7 @@ public function testBuiltinMetricsCanBeEnabled() new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper(), + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), 'gapicSpannerClient' => $gapicSpannerClient->reveal(), 'enableBuiltInMetrics' => true, ]); @@ -912,7 +912,7 @@ public function testSpannerClientInstantiatesWithoutDelayWhenMetricsDisabled() $start = microtime(true); new SpannerClient([ 'projectId' => self::PROJECT, - 'credentials' => new InsecureCredentialsWrapper() + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() ]); $end = microtime(true); From 2b795ebce32bba16a812cb66656785f1f0f82e8a Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Tue, 29 Sep 2026 21:38:08 +0000 Subject: [PATCH 11/15] fix(Core): extend Message in OperationResponseTraitTest Response stub --- Core/tests/Unit/LongRunning/OperationResponseTraitTest.php | 4 ++-- Gax/src/OperationResponse.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php index d47b162540d5..dc61548dc79f 100644 --- a/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php +++ b/Core/tests/Unit/LongRunning/OperationResponseTraitTest.php @@ -181,7 +181,7 @@ public function getValue() } } -class Response +class Response extends \Google\Protobuf\Internal\Message { public $metadataType; public $metadata; @@ -219,7 +219,7 @@ public function getError() return $this->error; } - public function serializeToJsonString() + public function serializeToJsonString($options = 0) { $result = [ 'done' => true, diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 2c6e53e40c72..35bde207400c 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -100,7 +100,7 @@ class OperationResponse * OperationResponse constructor. * * @param string|null $operationName - * @param object|null $operationsClient + * @param ServiceInterface|object|null $operationsClient * @param array $options { * Optional. Options for configuring the operation response object. * @@ -373,7 +373,7 @@ public function getLastProtoResponse(): ?object } /** - * @return object|null The OperationsClient object used to make + * @return ServiceInterface|object|null The OperationsClient object used to make * requests to the operations API. */ public function getOperationsClient(): ?object From 0d4dc83983ef9706f4176a5cab63ac2d80f57879 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 20:55:45 +0000 Subject: [PATCH 12/15] chore(Gax): remove Gax/tests/Testing from phpcs-ruleset.xml --- Gax/tests/Testing/MockGrpcTransport.php | 4 ++++ phpcs-ruleset.xml | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Gax/tests/Testing/MockGrpcTransport.php b/Gax/tests/Testing/MockGrpcTransport.php index 1c82f4a2ae08..8b1baa203146 100644 --- a/Gax/tests/Testing/MockGrpcTransport.php +++ b/Gax/tests/Testing/MockGrpcTransport.php @@ -56,6 +56,8 @@ public function __construct($mockCall = null, ?LoggerInterface $logger = null) parent::__construct('', $opts, logger: $logger); } + // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps,PSR2.Methods.MethodDeclaration.Underscore + /** * @param string $method * @param array $arguments @@ -116,6 +118,8 @@ protected function _bidiRequest( return $this->mockCall; } + // phpcs:enable + /** * @param string $method * @param callable $deserialize diff --git a/phpcs-ruleset.xml b/phpcs-ruleset.xml index f0f7082bd198..ef321333c1a9 100644 --- a/phpcs-ruleset.xml +++ b/phpcs-ruleset.xml @@ -26,7 +26,6 @@ Bigtable/tests/Conformance/proxy/src Core/src/Testing Gax/src/Testing - Gax/tests/Testing Gax/tests/Unit/GapicClientTraitTest.php GSuiteAddOns/external OsLogin/src/Common From f27fa47e53f0ea47a018d8ba06a8a41aba81de27 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 13 Nov 2026 19:32:51 +0000 Subject: [PATCH 13/15] docs(Gax): update MIGRATING.md with KnownTypes and getHeaderCredentials --- Gax/MIGRATING.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index e5b583b6920c..6c1ce8191292 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -17,6 +17,7 @@ Update your `google/gax` dependency to `^2.0`: ### Removed Classes, Interfaces, and Traits - **`Google\ApiCore\GPBType` and `Google\ApiCore\GPBLabel`**: Removed. Use `Google\Protobuf\Internal\GPBType` and `Google\Protobuf\Internal\GPBLabel` instead. +- **`Google\ApiCore\KnownTypes::GRPC_TYPES` and `Google\ApiCore\KnownTypes::JSON_TYPES`**: Removed. - **`Google\ApiCore\ServiceAddressTrait`**: Replaced by `Google\ApiCore\ApiEndpointTrait` (`self::normalizeServiceAddress()` is now `self::normalizeApiEndpoint()`). - **`Google\ApiCore\Transport\Grpc\UnaryInterceptorInterface`**: Removed. Extend `Grpc\Interceptor` directly instead. - **`Google\ApiCore\Testing\MockGrpcTransport`**: Moved to the internal test suite (`Google\ApiCore\Tests\Testing\MockGrpcTransport`) and is no longer distributed with the package. @@ -45,8 +46,8 @@ Update your `google/gax` dependency to `^2.0`: - **`Google\ApiCore\InsecureCredentialsWrapper`** now implements `Google\ApiCore\HeaderCredentialsInterface` directly and no longer extends `Google\ApiCore\CredentialsWrapper`. - **`Google\ApiCore\HeaderCredentialsInterface`** now extends `Google\Auth\GetQuotaProjectInterface`. -- **`GapicClientTrait::getCredentialsWrapper()`** now returns `HeaderCredentialsInterface` instead of `CredentialsWrapper`. -- **`ResumableUploadClient::__construct()`** now accepts `HeaderCredentialsInterface` instead of `CredentialsWrapper`. +- **`GapicClientTrait::getCredentialsWrapper()`** has been replaced by `GapicClientTrait::getHeaderCredentials()`, returning `HeaderCredentialsInterface` instead of `CredentialsWrapper` (and `ClientOptionsTrait::createCredentialsWrapper()` has been renamed to `ClientOptionsTrait::createHeaderCredentials()`). +- **`ResumableUploadClient::__construct()`** and **`CredentialsWrapperMiddleware::__construct()`** now accept `HeaderCredentialsInterface` instead of `CredentialsWrapper`. ### Strict Types and Method Signatures From 8b2f1a798414f5d002943650a1c2997502b20f7c Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 13 Nov 2026 19:56:31 +0000 Subject: [PATCH 14/15] chore(Gax): typehint OperationResponse::getLastProtoResponse(): ?Message --- Gax/src/OperationResponse.php | 14 +++--- Gax/tests/Unit/OperationResponseTest.php | 45 +++++-------------- .../mocks/CustomOperation/CustomOperation.php | 26 +++++++++-- .../CustomOperationWithErrorAnnotations.php | 35 +++++++++++++-- 4 files changed, 74 insertions(+), 46 deletions(-) diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 35bde207400c..a147a95748cb 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -81,7 +81,8 @@ class OperationResponse 'totalPollTimeoutMillis' => self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?object $lastProtoResponse; + /** @var Operation|Message|null */ + private ?Message $lastProtoResponse; private bool $deleted = false; private array $additionalArgs; @@ -110,7 +111,7 @@ class OperationResponse * @type int $pollDelayMultiplier Multiplier applied to the polling interval on each retry. * @type int $maxPollDelayMillis The maximum polling interval to use, in milliseconds. * @type int $totalPollTimeoutMillis The maximum amount of time to continue polling. - * @type object $lastProtoResponse A response already received from the server. + * @type Operation|Message $lastProtoResponse A response already received from the server. * @type string $getOperationMethod The method on $operationsClient to get the operation. * @type string $cancelOperationMethod The method on $operationsClient to cancel the operation. * @type string $deleteOperationMethod The method on $operationsClient to delete the operation. @@ -302,8 +303,9 @@ public function getResult(): mixed return null; } - /** @var Any|null $anyResponse */ - $anyResponse = $this->lastProtoResponse->getResponse(); + /** @var Operation $lastProtoResponse */ + $lastProtoResponse = $this->lastProtoResponse; + $anyResponse = $lastProtoResponse->getResponse(); if (is_null($anyResponse)) { return null; } @@ -365,9 +367,9 @@ public function getDescriptorOptions(): array } /** - * @return Operation|object|null The last Operation object received from the server. + * @return Operation|Message|null The last Operation object received from the server. */ - public function getLastProtoResponse(): ?object + public function getLastProtoResponse(): ?Message { return $this->lastProtoResponse; } diff --git a/Gax/tests/Unit/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 21715d65ded0..c7bd9be89e4f 100644 --- a/Gax/tests/Unit/OperationResponseTest.php +++ b/Gax/tests/Unit/OperationResponseTest.php @@ -229,17 +229,11 @@ public function pollingDataProvider() public function testCustomOperation() { $operationName = 'test-123'; - $operation = $this->prophesize(CustomOperation::class); - $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) - ->willReturn('Yes, it is!'); - $operation->getError() - ->shouldBeCalledOnce() - ->willReturn(null); + $operation = new CustomOperation('Yes, it is!', null); $operationClient = $this->prophesize(CustomOperationClient::class); $operationClient->getMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() - ->willReturn($operation->reveal()); + ->willReturn($operation); $operationClient->cancelMyOperationPlease(Argument::type(Message::class)) ->shouldBeCalledOnce() ->willReturn(true); @@ -283,7 +277,10 @@ public function testNewSurfaceCustomOperation() $phpunit->assertEquals('test-123', $request->name); $phpunit->assertEquals('arg2', $request->arg2); $phpunit->assertEquals('arg3', $request->arg3); - return new class { + return new class extends Message { + public function __construct() + { + } public function getDone() { return true; @@ -362,22 +359,13 @@ public function testRequestClassWithoutBuildThrowsException() public function testCustomOperationError($operationClient) { $operationName = 'test-123'; - $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); - $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledTimes(2) - ->willReturn('Yes, it is!'); - $operation->getTheErrorCode() - ->shouldBeCalledTimes(2) - ->willReturn(500); - $operation->getTheErrorMessage() - ->shouldBeCalledOnce() - ->willReturn('It failed, sorry :('); + $operation = new CustomOperationWithErrorAnnotations('Yes, it is!', 500, 'It failed, sorry :('); $options = [ 'operationStatusMethod' => 'isThisOperationDoneOrWhat', 'operationStatusDoneValue' => 'Yes, it is!', 'operationErrorCodeMethod' => 'getTheErrorCode', 'operationErrorMessageMethod' => 'getTheErrorMessage', - 'lastProtoResponse' => $operation->reveal(), + 'lastProtoResponse' => $operation, ]; $operationResponse = new OperationResponse($operationName, $operationClient, $options); @@ -396,18 +384,12 @@ public function testCustomOperationError($operationClient) public function testEmptyCustomOperationErrorIsSuccessful($operationClient) { $operationName = 'test-123'; - $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); - $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() - ->willReturn('Yes, it is!'); - $operation->getTheErrorCode() - ->shouldBeCalledOnce() - ->willReturn(null); + $operation = new CustomOperationWithErrorAnnotations('Yes, it is!', null); $options = [ 'operationStatusMethod' => 'isThisOperationDoneOrWhat', 'operationStatusDoneValue' => 'Yes, it is!', 'operationErrorCodeMethod' => 'getTheErrorCode', - 'lastProtoResponse' => $operation->reveal(), + 'lastProtoResponse' => $operation, ]; $operationResponse = new OperationResponse($operationName, $operationClient, $options); @@ -420,15 +402,12 @@ public function testEmptyCustomOperationErrorIsSuccessful($operationClient) public function testMisconfiguredCustomOperationThrowsException($operationClient) { $operationName = 'test-123'; - $operation = $this->prophesize(CustomOperationWithErrorAnnotations::class); - $operation->isThisOperationDoneOrWhat() - ->shouldBeCalledOnce() - ->willReturn('Yes, it is!'); + $operation = new CustomOperationWithErrorAnnotations('Yes, it is!'); $options = [ 'operationStatusMethod' => 'isThisOperationDoneOrWhat', 'operationStatusDoneValue' => 'Yes, it is!', 'operationErrorCodeMethod' => null, // The OperationResponse has no way to determine error status - 'lastProtoResponse' => $operation->reveal(), + 'lastProtoResponse' => $operation, ]; $operationResponse = new OperationResponse($operationName, $operationClient, $options); diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperation.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperation.php index 53a4fad492d3..fed076f31ec3 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperation.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperation.php @@ -2,8 +2,28 @@ namespace Google\CustomOperation; -interface CustomOperation +use Google\Protobuf\Internal\Message; + +class CustomOperation extends Message { - public function isThisOperationDoneOrWhat(); - public function getError(); + private static string $status; + private static mixed $error; + + public function __construct( + string $status = 'Yes, it is!', + mixed $error = null + ) { + self::$status = $status; + self::$error = $error; + } + + public function isThisOperationDoneOrWhat() + { + return self::$status; + } + + public function getError() + { + return self::$error; + } } diff --git a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationWithErrorAnnotations.php b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationWithErrorAnnotations.php index 02a6c87acf5e..e5bf1ac91cbe 100644 --- a/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationWithErrorAnnotations.php +++ b/Gax/tests/Unit/testdata/mocks/CustomOperation/CustomOperationWithErrorAnnotations.php @@ -2,9 +2,36 @@ namespace Google\CustomOperation; -interface CustomOperationWithErrorAnnotations +use Google\Protobuf\Internal\Message; + +class CustomOperationWithErrorAnnotations extends Message { - public function isThisOperationDoneOrWhat(); - public function getTheErrorCode(); - public function getTheErrorMessage(); + private static string $status; + private static ?int $errorCode; + private static ?string $errorMessage; + + public function __construct( + string $status = 'Yes, it is!', + ?int $errorCode = null, + ?string $errorMessage = null + ) { + self::$status = $status; + self::$errorCode = $errorCode; + self::$errorMessage = $errorMessage; + } + + public function isThisOperationDoneOrWhat() + { + return self::$status; + } + + public function getTheErrorCode() + { + return self::$errorCode; + } + + public function getTheErrorMessage() + { + return self::$errorMessage; + } } From e5f3a595f961e228be0725e6f6f5627cae0de6b6 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Mon, 16 Nov 2026 23:03:21 +0000 Subject: [PATCH 15/15] chore(Gax): graduate client interfaces by removing @experimental and @internal --- Gax/src/IamProviderInterface.php | 3 --- Gax/src/LongRunningOperationProviderInterface.php | 3 --- Gax/src/ServiceInterface.php | 3 --- 3 files changed, 9 deletions(-) diff --git a/Gax/src/IamProviderInterface.php b/Gax/src/IamProviderInterface.php index e33621dabd16..92b41802ee31 100644 --- a/Gax/src/IamProviderInterface.php +++ b/Gax/src/IamProviderInterface.php @@ -43,9 +43,6 @@ /** * Interface implemented by GAPIC service clients that expose IAM policy * management methods (`getIamPolicy`, `setIamPolicy`, and `testIamPermissions`). - * - * @experimental - * @internal */ interface IamProviderInterface { diff --git a/Gax/src/LongRunningOperationProviderInterface.php b/Gax/src/LongRunningOperationProviderInterface.php index 4635ad6d14d2..ff9c39a35bac 100644 --- a/Gax/src/LongRunningOperationProviderInterface.php +++ b/Gax/src/LongRunningOperationProviderInterface.php @@ -39,9 +39,6 @@ /** * Interface implemented by GAPIC service clients that support standard * Google Cloud Long-Running Operations (LROs). - * - * @experimental - * @internal */ interface LongRunningOperationProviderInterface { diff --git a/Gax/src/ServiceInterface.php b/Gax/src/ServiceInterface.php index 11ea07b3eb92..98f445053105 100644 --- a/Gax/src/ServiceInterface.php +++ b/Gax/src/ServiceInterface.php @@ -37,9 +37,6 @@ /** * Interface implemented by all GAPIC service clients, defining common lifecycle, * scope, and middleware configuration methods. - * - * @experimental - * @internal */ interface ServiceInterface {