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/MIGRATING.md b/Gax/MIGRATING.md new file mode 100644 index 000000000000..6c1ce8191292 --- /dev/null +++ b/Gax/MIGRATING.md @@ -0,0 +1,56 @@ +# 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\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. + +### Removed Dependencies + +- **`google/grpc-gcp`**: Removed along with the `gcpApiConfigPath` client option, `ClientOptionsTrait::initGrpcGcpConfig()`, and `Grpc\Gcp\GCPServerStreamCall` handling in `ServerStreamingCallWrapper`. + +### Removed Options + +- **`gcpApiConfigPath` client option**: Removed along with `google/grpc-gcp`. +- **`operationsClientClass` client option**: Removed. Pass a pre-constructed client via the `operationsClient` option instead. +- **`CallOptions::setTransportSpecificOptions()`**: Removed. Use `CallOptions::setTransportOptions()` instead. + +### Removed Methods and Legacy V1 Client Surface Support + +- **`CredentialsWrapper::getBearerString()`**: Removed. Use `CredentialsWrapper::getAuthorizationHeaderCallback()` 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`. + - 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()`** 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 + +- Added `declare(strict_types=1)` across all `Google\ApiCore` files. +- 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/AgentHeader.php b/Gax/src/AgentHeader.php index 4fda2b0e9a98..7365748b2bed 100644 --- a/Gax/src/AgentHeader.php +++ b/Gax/src/AgentHeader.php @@ -1,4 +1,6 @@ getFileName(); $versionFile = substr( $callingClassFile, 0, - strrpos($callingClassFile, DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR) + strrpos($callingClassFile, DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR) ?: 0 ) . DIRECTORY_SEPARATOR . 'VERSION'; return Version::readVersionFile($versionFile); diff --git a/Gax/src/ApiException.php b/Gax/src/ApiException.php index 9133a02f4a43..dfc881dfe5b6 100644 --- a/Gax/src/ApiException.php +++ b/Gax/src/ApiException.php @@ -1,4 +1,6 @@ protobufErrors = $protobufErrors; } - public function getStatus() + public function getStatus(): ?string { return $this->status; } @@ -96,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. @@ -117,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; } @@ -126,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; } @@ -135,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; } @@ -153,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 = []; @@ -171,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, @@ -197,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, @@ -226,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 []; @@ -260,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 = [ @@ -334,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(), @@ -354,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. @@ -385,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/ApiKeyHeaderCredentials.php b/Gax/src/ApiKeyHeaderCredentials.php index f4471d6e94f1..9c84509ec8cc 100644 --- a/Gax/src/ApiKeyHeaderCredentials.php +++ b/Gax/src/ApiKeyHeaderCredentials.php @@ -1,4 +1,6 @@ $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 e4d6718b25e6..58608a89bb2c 100644 --- a/Gax/src/BidiStream.php +++ b/Gax/src/BidiStream.php @@ -1,4 +1,6 @@ isComplete) { throw new ValidationException('Cannot call write() after streaming call is complete.'); @@ -107,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); @@ -119,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( @@ -140,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.'); @@ -193,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(); @@ -208,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 adcc77e19457..ace8d4b36f37 100644 --- a/Gax/src/Call.php +++ b/Gax/src/Call.php @@ -1,4 +1,6 @@ method = $method; @@ -77,7 +79,7 @@ public function __construct( /** * @return string */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -85,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; } @@ -101,7 +103,7 @@ public function getDecodeType() /** * @return mixed|Message */ - public function getMessage() + public function getMessage(): mixed { return $this->message; } @@ -109,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 5fdccdd39889..af368900c690 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -1,4 +1,6 @@ toArray(); @@ -179,10 +181,12 @@ private function buildClientOptions(array|ClientOptions $options) 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 @@ -227,18 +231,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']; - } + $apiEndpoint = defined('self::SERVICE_ADDRESS_TEMPLATE') + ? str_replace('UNIVERSE_DOMAIN', $options['universeDomain'], self::SERVICE_ADDRESS_TEMPLATE) + : $defaultOptions['apiEndpoint']; } $options['apiEndpoint'] = $apiEndpoint; @@ -246,7 +241,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) { @@ -259,7 +254,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) { @@ -271,13 +266,16 @@ private static function determineMtlsEndpoint(string $apiEndpoint) /** * @param string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * @param array $credentialsConfig + * @param string $universeDomain * @return HeaderCredentialsInterface * @throws ValidationException */ - private function createCredentialsWrapper($credentials, array $credentialsConfig, string $universeDomain) - { + private function createCredentialsWrapper( + string|array|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); } @@ -290,21 +288,14 @@ private function createCredentialsWrapper($credentials, array $credentialsConfig return new CredentialsWrapper($credentials, $authHttpHandler, $universeDomain); } - if ($credentials instanceof HeaderCredentialsInterface) { - 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 6c249551ca54..28abd96f8063 100644 --- a/Gax/src/ClientStream.php +++ b/Gax/src/ClientStream.php @@ -1,4 +1,6 @@ logger && $request instanceof Message) { @@ -91,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) { @@ -123,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); @@ -134,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 80cc9e0c14a0..20517a017971 100644 --- a/Gax/src/CredentialsWrapper.php +++ b/Gax/src/CredentialsWrapper.php @@ -1,4 +1,6 @@ null, 'scopes' => null, @@ -219,10 +221,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 @@ -307,10 +309,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, @@ -331,7 +333,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); @@ -340,7 +342,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 03ec835c1368..94549f760a6e 100644 --- a/Gax/src/FixedSizeCollection.php +++ b/Gax/src/FixedSizeCollection.php @@ -1,4 +1,6 @@ pageList as $page) { @@ -94,7 +97,7 @@ public function getCollectionSize() * * @return bool */ - public function hasNextCollection() + public function hasNextCollection(): bool { return $this->getLastPage()->hasNextPage(); } @@ -105,7 +108,7 @@ public function hasNextCollection() * * @return string */ - public function getNextPageToken() + public function getNextPageToken(): string { return $this->getLastPage()->getNextPageToken(); } @@ -115,7 +118,7 @@ public function getNextPageToken() * * @return FixedSizeCollection */ - public function getNextCollection() + public function getNextCollection(): self { $lastPage = $this->getLastPage(); $nextPage = $lastPage->getNextPage($this->collectionSize); @@ -127,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) { @@ -142,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; @@ -154,7 +156,7 @@ public function iterateCollections() } } - private function getLastPage() + private function getLastPage(): Page { $pageList = $this->pageList; // Get last element in array... @@ -168,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 48d58dea55a9..d1f24bdda0d6 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -1,4 +1,6 @@ handler)($call, $options); * // modify the response (post-request) @@ -137,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) @@ -183,9 +191,9 @@ public function close(): void * use by customized clients. * * @access private - * @return TransportInterface + * @return ?TransportInterface */ - protected function getTransport() + protected function getTransport(): ?TransportInterface { return $this->transport; } @@ -195,9 +203,9 @@ protected function getTransport() * use by customized clients. * * @access private - * @return HeaderCredentialsInterface + * @return ?HeaderCredentialsInterface */ - protected function getCredentialsWrapper() + protected function getCredentialsWrapper(): ?HeaderCredentialsInterface { return $this->credentialsWrapper; } @@ -265,7 +273,7 @@ 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'])) { @@ -293,7 +301,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( @@ -374,17 +381,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( @@ -432,37 +433,39 @@ private function createTransport( } /** - * @param array $options - * @return OperationsClient|object + * 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 return new OperationsClient($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])) { @@ -483,8 +486,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'"); } @@ -527,7 +530,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); @@ -570,13 +573,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']; @@ -643,7 +646,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) @@ -686,7 +689,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()) { @@ -744,7 +747,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'] ?? []; @@ -769,7 +772,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(); } @@ -794,10 +796,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) @@ -852,7 +854,7 @@ private function getPagedListResponse( string $decodeType, Message $request, ?string $interfaceName = null - ) { + ): PagedListResponse { return $this->getPagedListResponseAsync( $methodName, $optionalArgs, @@ -877,7 +879,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']; @@ -915,7 +917,7 @@ private function getPagedListResponseAsync( string $decodeType, Message $request, ?string $interfaceName = null - ) { + ): PromiseInterface { $optionalArgs = $this->configureCallOptions($optionalArgs); $callStack = $this->createCallStack( $this->configureCallConstructionOptions($methodName, $optionalArgs) @@ -945,7 +947,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', @@ -960,7 +962,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 = []; @@ -1016,7 +1018,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/GrpcSupportTrait.php b/Gax/src/GrpcSupportTrait.php index 85251eeeebc4..a9418b70ccae 100644 --- a/Gax/src/GrpcSupportTrait.php +++ b/Gax/src/GrpcSupportTrait.php @@ -1,4 +1,6 @@ \Google\Rpc\RetryInfo::class, 'google.rpc.debuginfo-bin' => \Google\Rpc\DebugInfo::class, 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/Middleware/CredentialsWrapperMiddleware.php b/Gax/src/Middleware/CredentialsWrapperMiddleware.php index aca4425fad9a..b6e1ffb4aa34 100644 --- a/Gax/src/Middleware/CredentialsWrapperMiddleware.php +++ b/Gax/src/Middleware/CredentialsWrapperMiddleware.php @@ -1,4 +1,6 @@ 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 f3204b5483ce..1c0e2469dda5 100644 --- a/Gax/src/Middleware/FixedHeaderMiddleware.php +++ b/Gax/src/Middleware/FixedHeaderMiddleware.php @@ -1,4 +1,6 @@ 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 c5c60d58c14d..004cce465f98 100644 --- a/Gax/src/Middleware/MiddlewareInterface.php +++ b/Gax/src/Middleware/MiddlewareInterface.php @@ -1,4 +1,6 @@ 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); + * } * } * ``` * @@ -88,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 e7f9baca6985..07bbe42cc23c 100644 --- a/Gax/src/Middleware/OperationsMiddleware.php +++ b/Gax/src/Middleware/OperationsMiddleware.php @@ -1,4 +1,6 @@ nextHandler = $nextHandler; @@ -57,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 d5027fe4b948..23fe9bf8b655 100644 --- a/Gax/src/Middleware/OptionsFilterMiddleware.php +++ b/Gax/src/Middleware/OptionsFilterMiddleware.php @@ -1,4 +1,6 @@ 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 b396281e94cd..8ea8c70b88a1 100644 --- a/Gax/src/Middleware/PagedMiddleware.php +++ b/Gax/src/Middleware/PagedMiddleware.php @@ -1,4 +1,6 @@ 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 4811664eae44..fb1cbb98be5e 100644 --- a/Gax/src/Middleware/RequestAutoPopulationMiddleware.php +++ b/Gax/src/Middleware/RequestAutoPopulationMiddleware.php @@ -1,4 +1,6 @@ */ - private $autoPopulationSettings; + /** @var array */ + private array $autoPopulationSettings; public function __construct( callable $nextHandler, @@ -63,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 c9dbdef218dd..14867233dd11 100644 --- a/Gax/src/Middleware/ResponseMetadataMiddleware.php +++ b/Gax/src/Middleware/ResponseMetadataMiddleware.php @@ -1,4 +1,6 @@ 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 10603e2627df..db7c01615df7 100644 --- a/Gax/src/Middleware/RetryMiddleware.php +++ b/Gax/src/Middleware/RetryMiddleware.php @@ -1,4 +1,6 @@ nextHandler = $nextHandler; @@ -75,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'])) { @@ -132,17 +139,20 @@ 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(); $maxTimeoutMs = $this->retrySettings->getMaxRpcTimeoutMillis(); - $delayMs = $this->retrySettings->getInitialRetryDelayMillis(); + $delayMs = (int) $this->retrySettings->getInitialRetryDelayMillis(); $timeoutMs = $options['timeoutMillis']; $currentTimeMs = $this->getCurrentTimeMs(); @@ -154,7 +164,7 @@ private function retry(Call $call, array $options, string $status) ); } - $nextDelayMs = min($delayMs * $delayMult, $maxDelayMs); + $nextDelayMs = (int) min($delayMs * $delayMult, $maxDelayMs); $timeoutMs = (int) min( $timeoutMs * $timeoutMult, $maxTimeoutMs, @@ -183,7 +193,7 @@ private function retry(Call $call, array $options, string $status) ); } - protected function getCurrentTimeMs() + protected function getCurrentTimeMs(): float { return microtime(true) * 1000.0; } @@ -191,7 +201,7 @@ protected function getCurrentTimeMs() /** * This is the default retry behaviour. */ - private function getRetryFunction() + private function getRetryFunction(): callable { return $this->retrySettings->getRetryFunction() ?? function (\Throwable $e, array $options): bool { @@ -213,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 1306f78e11d0..5adddd1776fe 100644 --- a/Gax/src/Middleware/TransportCallMiddleware.php +++ b/Gax/src/Middleware/TransportCallMiddleware.php @@ -1,4 +1,6 @@ transportCallMethods[$call->getCallType()]; return $this->transport->$startCallMethod($call, $options); } diff --git a/Gax/src/OperationResponse.php b/Gax/src/OperationResponse.php index 51c39770a6d6..a147a95748cb 100644 --- a/Gax/src/OperationResponse.php +++ b/Gax/src/OperationResponse.php @@ -1,4 +1,6 @@ self::DEFAULT_MAX_POLLING_DURATION, ]; - private ?object $lastProtoResponse; + /** @var Operation|Message|null */ + private ?Message $lastProtoResponse; private bool $deleted = false; private array $additionalArgs; @@ -90,16 +93,15 @@ class OperationResponse private ?string $cancelOperationRequest; private ?string $deleteOperationRequest; private string $operationStatusMethod; - /** @var mixed */ - private $operationStatusDoneValue; + private mixed $operationStatusDoneValue; private ?string $operationErrorCodeMethod; private ?string $operationErrorMessageMethod; /** * OperationResponse constructor. * - * @param string $operationName - * @param object|null $operationsClient + * @param string|null $operationName + * @param ServiceInterface|object|null $operationsClient * @param array $options { * Optional. Options for configuring the operation response object. * @@ -109,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. @@ -120,7 +122,7 @@ class OperationResponse * @type string $operationErrorMessageMethod The method on the operation to get the error status * } */ - public function __construct(string $operationName, $operationsClient, array $options = []) + public function __construct(?string $operationName, ?object $operationsClient, array $options = []) { $this->operationName = $operationName; $this->operationsClient = $operationsClient; @@ -174,7 +176,7 @@ public function __construct(string $operationName, $operationsClient, array $opt * * @return bool */ - public function isDone() + public function isDone(): bool { if (!$this->hasProtoResponse()) { return false; @@ -194,7 +196,7 @@ public function isDone() * * @return bool */ - public function operationSucceeded() + public function operationSucceeded(): bool { if (!$this->hasProtoResponse()) { return false; @@ -215,7 +217,7 @@ public function operationSucceeded() * * @return bool */ - public function operationFailed() + public function operationFailed(): bool { return $this->hasErrors(); } @@ -223,9 +225,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; } @@ -250,7 +252,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; @@ -269,13 +271,16 @@ 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'); } - $this->lastProtoResponse = $this->operationsCall($this->getOperationMethod, $this->getOperationRequest); + $this->lastProtoResponse = $this->operationsCall( + $this->getOperationMethod, + $this->getOperationRequest + ); } /** @@ -284,7 +289,7 @@ public function reload() * * @return T|null */ - public function getResult() + public function getResult(): mixed { if (!$this->hasProtoResponse()) { return null; @@ -298,8 +303,9 @@ public function getResult() 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; } @@ -316,10 +322,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; @@ -352,7 +358,7 @@ public function getError() * * @return array */ - public function getDescriptorOptions() + public function getDescriptorOptions(): array { return [ 'operationReturnType' => $this->operationReturnType, @@ -361,18 +367,18 @@ public function getDescriptorOptions() } /** - * @return Operation|mixed|null The last Operation object received from the server. + * @return Operation|Message|null The last Operation object received from the server. */ - public function getLastProtoResponse() + public function getLastProtoResponse(): ?Message { return $this->lastProtoResponse; } /** - * @return object The OperationsClient object used to make + * @return ServiceInterface|object|null The OperationsClient object used to make * requests to the operations API. */ - public function getOperationsClient() + public function getOperationsClient(): ?object { return $this->operationsClient; } @@ -394,7 +400,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'); @@ -414,7 +420,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'); @@ -431,7 +437,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; @@ -451,10 +457,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(); @@ -467,13 +469,14 @@ public function getMetadata() * * @param string $method The method to call on the operations client. * @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'); } - // 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( @@ -483,14 +486,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; @@ -509,7 +512,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 2b67bd8367f4..1df2088183a2 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -1,4 +1,6 @@ retrySettings = $retrySettings; diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index af3c8aaadbb6..66ea4affe48a 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -1,4 +1,6 @@ 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; @@ -250,8 +246,9 @@ public function setClientConfig($clientConfig): self * * @return $this */ - public function setCredentials($credentials): self - { + public function setCredentials( + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials + ): self { $this->credentials = $credentials; return $this; @@ -274,7 +271,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/Options/OptionsInterface.php b/Gax/src/Options/OptionsInterface.php index 684d27e65cbd..910b27ae8564 100644 --- a/Gax/src/Options/OptionsInterface.php +++ b/Gax/src/Options/OptionsInterface.php @@ -1,4 +1,6 @@ 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(); } /** @@ -110,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( @@ -159,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()); } /** @@ -170,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; @@ -189,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; @@ -208,7 +210,7 @@ public function iteratePages() * * @return mixed|Message */ - public function getRequestObject() + public function getRequestObject(): mixed { return $this->call->getMessage(); } @@ -216,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; } @@ -239,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/PageStreamingDescriptor.php b/Gax/src/PageStreamingDescriptor.php index 351eaf7fc3ec..b7c939984da2 100644 --- a/Gax/src/PageStreamingDescriptor.php +++ b/Gax/src/PageStreamingDescriptor.php @@ -1,4 +1,6 @@ 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); } @@ -130,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']; } @@ -138,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']; } @@ -146,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/PagedListResponse.php b/Gax/src/PagedListResponse.php index 62e6511eebef..c63a9758329d 100644 --- a/Gax/src/PagedListResponse.php +++ b/Gax/src/PagedListResponse.php @@ -1,4 +1,6 @@ getIterator(); } @@ -121,8 +124,7 @@ public function iterateAllElements() * @return Generator * @throws ValidationException */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): Traversable { foreach ($this->iteratePages() as $page) { foreach ($page as $key => $element) { @@ -136,7 +138,7 @@ public function getIterator() * * @return Page */ - public function getPage() + public function getPage(): Page { return $this->firstPage; } @@ -145,10 +147,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(); } @@ -168,7 +170,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); } @@ -188,9 +190,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/PathTemplate.php b/Gax/src/PathTemplate.php index 464f32dc1ffb..8864e5734878 100644 --- a/Gax/src/PathTemplate.php +++ b/Gax/src/PathTemplate.php @@ -1,4 +1,6 @@ resourceTemplate->__toString(); } @@ -83,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); } @@ -94,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); } @@ -106,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/PollingTrait.php b/Gax/src/PollingTrait.php index 526b01255f68..8967f8fa44f7 100644 --- a/Gax/src/PollingTrait.php +++ b/Gax/src/PollingTrait.php @@ -1,4 +1,6 @@ getCurrentTimeMillis() > $endTime) { return false; } - $this->sleepMillis($currentPollDelayMillis); + $this->sleepMillis((int) $currentPollDelayMillis); if ($pollCallable()) { return true; } @@ -80,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; } @@ -90,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/RequestBuilder.php b/Gax/src/RequestBuilder.php index 24af4c050d04..d4fb3d560c74 100644 --- a/Gax/src/RequestBuilder.php +++ b/Gax/src/RequestBuilder.php @@ -1,4 +1,6 @@ restConfig['interfaces'][$interface][$method]); @@ -82,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); @@ -142,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]; @@ -160,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(); @@ -227,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) { @@ -254,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); @@ -270,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 73e9af3317c8..90d17df8bb1e 100644 --- a/Gax/src/RequestParamsHeaderDescriptor.php +++ b/Gax/src/RequestParamsHeaderDescriptor.php @@ -1,4 +1,6 @@ header; } diff --git a/Gax/src/ResourceHelperTrait.php b/Gax/src/ResourceHelperTrait.php index 7f168413b338..2587de5c43b7 100644 --- a/Gax/src/ResourceHelperTrait.php +++ b/Gax/src/ResourceHelperTrait.php @@ -1,4 +1,6 @@ |null */ + private static ?array $templateMap = null; /** * placeholder for this function like we have in GapicClientTrait @@ -51,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; } @@ -73,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/AbsoluteResourceTemplate.php b/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php index de08c38c7d59..16de78aed1fc 100644 --- a/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php +++ b/Gax/src/ResourceTemplate/AbsoluteResourceTemplate.php @@ -1,4 +1,6 @@ resourceTemplate, $this->renderVerb()); } @@ -88,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()); } @@ -96,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); @@ -109,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'); @@ -124,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 2bc70ad330c8..aa74e1c3dc3d 100644 --- a/Gax/src/ResourceTemplate/Parser.php +++ b/Gax/src/ResourceTemplate/Parser.php @@ -1,4 +1,6 @@ = strlen($path)) { // A trailing '/' has caused the index to exceed the bounds @@ -133,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); @@ -158,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, '{'); @@ -194,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)) { @@ -208,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"); } @@ -220,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 12d2abfb48b7..32e19f8a42e0 100644 --- a/Gax/src/ResourceTemplate/RelativeResourceTemplate.php +++ b/Gax/src/ResourceTemplate/RelativeResourceTemplate.php @@ -1,4 +1,6 @@ segments); } @@ -101,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); @@ -129,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, @@ -197,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); @@ -210,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 @@ -331,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( @@ -350,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; @@ -383,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)) { @@ -417,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) { @@ -438,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++) { @@ -456,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 ffa3c8138da5..bcdd9ab2728e 100644 --- a/Gax/src/ResourceTemplate/ResourceTemplateInterface.php +++ b/Gax/src/ResourceTemplate/ResourceTemplateInterface.php @@ -1,4 +1,6 @@ stringRepr; } @@ -111,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: @@ -132,7 +134,7 @@ public function matches(string $value) /** * @return int */ - public function getSegmentType() + public function getSegmentType(): int { return $this->segmentType; } @@ -140,7 +142,7 @@ public function getSegmentType() /** * @return string|null */ - public function getKey() + public function getKey(): ?string { return $this->key; } @@ -148,7 +150,7 @@ public function getKey() /** * @return string|null */ - public function getValue() + public function getValue(): ?string { return $this->value; } @@ -156,7 +158,7 @@ public function getValue() /** * @return RelativeResourceTemplate|null */ - public function getTemplate() + public function getTemplate(): ?RelativeResourceTemplate { return $this->template; } @@ -164,7 +166,7 @@ public function getTemplate() /** * @return string */ - public function getSeparator() + public function getSeparator(): string { return $this->separator; } @@ -176,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; } @@ -188,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/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 @@ 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/ResumableUploadState.php b/Gax/src/ResumableUpload/ResumableUploadState.php index a184f4626332..41324a3b257c 100644 --- a/Gax/src/ResumableUpload/ResumableUploadState.php +++ b/Gax/src/ResumableUpload/ResumableUploadState.php @@ -1,4 +1,6 @@ false, @@ -391,7 +393,7 @@ public static function constructDefault() * } * @return RetrySettings */ - public function with(array $settings) + public function with(array $settings): self { $existingSettings = [ 'initialRetryDelayMillis' => $this->getInitialRetryDelayMillis(), @@ -417,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, @@ -431,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; } @@ -440,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; } @@ -457,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; } @@ -475,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; } @@ -485,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; } @@ -504,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; } @@ -515,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; } @@ -523,7 +525,7 @@ public function getTotalTimeoutMillis() /** * @experimental */ - public function getMaxRetries() + public function getMaxRetries(): int { return $this->maxRetries; } @@ -531,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/Serializer.php b/Gax/src/Serializer.php index b65fffdebfaa..35f193a9b318 100644 --- a/Gax/src/Serializer.php +++ b/Gax/src/Serializer.php @@ -1,4 +1,6 @@ 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 []; @@ -222,7 +225,7 @@ public static function decodeMetadata(array $metadata, ?array &$errors = null) foreach ($metadata as $key => $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]; /** @@ -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/ServerStream.php b/Gax/src/ServerStream.php index 3257e65504fa..fb63ddf307a3 100644 --- a/Gax/src/ServerStream.php +++ b/Gax/src/ServerStream.php @@ -1,4 +1,6 @@ |mixed + * @return \Generator */ - public function readAll() + public function readAll(): iterable { $resourcesGetMethod = $this->resourcesGetMethod; foreach ($this->call->responses() as $response) { @@ -121,7 +123,7 @@ public function readAll() * * @return ServerStreamingCallInterface */ - public function getServerStreamingCall() + public function getServerStreamingCall(): ServerStreamingCallInterface { return $this->call; } diff --git a/Gax/src/ServerStreamingCallInterface.php b/Gax/src/ServerStreamingCallInterface.php index a78ff275edb9..26f81276d188 100644 --- a/Gax/src/ServerStreamingCallInterface.php +++ b/Gax/src/ServerStreamingCallInterface.php @@ -1,4 +1,6 @@ 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. @@ -91,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/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 { diff --git a/Gax/src/Testing/GeneratedTest.php b/Gax/src/Testing/GeneratedTest.php index f8d4c1af45a3..41fe7d3284ac 100644 --- a/Gax/src/Testing/GeneratedTest.php +++ b/Gax/src/Testing/GeneratedTest.php @@ -1,4 +1,6 @@ responses = $responses; $this->deserialize = $deserialize; @@ -73,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); @@ -100,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( @@ -128,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( @@ -149,7 +151,7 @@ public function write($request, array $options = []) /** * Set writesDone to true */ - public function writesDone() + public function writesDone(): void { $this->writesDone = true; } @@ -159,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 ca28e3dbf24c..e493126398df 100644 --- a/Gax/src/Testing/MockClientStreamingCall.php +++ b/Gax/src/Testing/MockClientStreamingCall.php @@ -1,4 +1,6 @@ mockUnaryCall = new MockUnaryCall($response, $deserialize, $status); } @@ -71,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(); @@ -83,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); @@ -102,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 d0dcead5d2bf..744ee9edca71 100644 --- a/Gax/src/Testing/MockServerStreamingCall.php +++ b/Gax/src/Testing/MockServerStreamingCall.php @@ -1,4 +1,6 @@ responses = $responses; $this->deserialize = $deserialize; @@ -71,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); @@ -84,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( @@ -95,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 6f290635631b..b2ffd89a951e 100644 --- a/Gax/src/Testing/MockStatus.php +++ b/Gax/src/Testing/MockStatus.php @@ -1,4 +1,6 @@ code = $code; $this->details = $details; diff --git a/Gax/src/Testing/MockStubTrait.php b/Gax/src/Testing/MockStubTrait.php index db69910aafbe..b4792e0ea428 100644 --- a/Gax/src/Testing/MockStubTrait.php +++ b/Gax/src/Testing/MockStubTrait.php @@ -1,4 +1,6 @@ receivedFuncCalls[] = new ReceivedRequest($method, $argument, $deserialize, $metadata, $options); if (count($this->responses) < 1) { throw new UnderflowException('ran out of responses'); @@ -103,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'); @@ -135,7 +138,7 @@ public function _serverStreamRequest( $deserialize, array $metadata = [], array $options = [] - ) { + ): MockServerStreamingCall { if (is_a($argument, '\Google\Protobuf\Internal\Message')) { /** @var Message $newArgument */ @@ -170,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); @@ -180,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) { @@ -193,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']; @@ -213,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; } @@ -223,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 = []; @@ -233,7 +236,7 @@ public function popReceivedCalls() /** * @return int The number of calls received. */ - public function getReceivedCallCount() + public function getReceivedCallCount(): int { return count($this->receivedFuncCalls); } @@ -241,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 = []; @@ -251,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; @@ -260,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; @@ -273,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 333cb0b519d8..e82860b63a62 100644 --- a/Gax/src/Testing/MockTransport.php +++ b/Gax/src/Testing/MockTransport.php @@ -1,4 +1,6 @@ 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( @@ -72,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]; @@ -107,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 431b041bfa47..47bdf2bd0315 100644 --- a/Gax/src/Testing/MockUnaryCall.php +++ b/Gax/src/Testing/MockUnaryCall.php @@ -1,4 +1,6 @@ response = $response; $this->deserialize = $deserialize; @@ -73,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/ProtobufGPBEmptyComparator.php b/Gax/src/Testing/ProtobufGPBEmptyComparator.php index b6871a8e4884..5c639c4dbc76 100644 --- a/Gax/src/Testing/ProtobufGPBEmptyComparator.php +++ b/Gax/src/Testing/ProtobufGPBEmptyComparator.php @@ -1,4 +1,6 @@ actualCall = [ 'funcCall' => $funcCall, 'request' => $requestObject, @@ -52,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 c703f0dea310..a183f4e2533d 100644 --- a/Gax/src/Testing/SerializationTrait.php +++ b/Gax/src/Testing/SerializationTrait.php @@ -1,4 +1,6 @@ innerCall = $innerCall; } @@ -59,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(); } @@ -67,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(); } @@ -83,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 10e4ee706f37..2578ca748d0e 100644 --- a/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php +++ b/Gax/src/Transport/Grpc/ForwardingServerStreamingCall.php @@ -1,4 +1,6 @@ innerCall->responses(); } @@ -55,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 81b00646dafd..5126c7c8c1a3 100644 --- a/Gax/src/Transport/Grpc/ForwardingUnaryCall.php +++ b/Gax/src/Transport/Grpc/ForwardingUnaryCall.php @@ -1,4 +1,6 @@ innerCall->wait(); } diff --git a/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php b/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php index 74ccf1429afc..99b6a4099391 100644 --- a/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php +++ b/Gax/src/Transport/Grpc/ServerStreamingCallWrapper.php @@ -1,4 +1,6 @@ stream = $stream; } @@ -57,7 +55,7 @@ public function __construct($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); } @@ -65,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; @@ -75,7 +73,7 @@ public function responses() /** * {@inheritdoc} */ - public function getStatus() + public function getStatus(): ?stdClass { return $this->stream->getStatus(); } @@ -83,7 +81,7 @@ public function getStatus() /** * {@inheritdoc} */ - public function getMetadata() + public function getMetadata(): mixed { return $this->stream->getMetadata(); } @@ -91,7 +89,7 @@ public function getMetadata() /** * {@inheritdoc} */ - public function getTrailingMetadata() + public function getTrailingMetadata(): mixed { return $this->stream->getTrailingMetadata(); } @@ -99,7 +97,7 @@ public function getTrailingMetadata() /** * {@inheritdoc} */ - public function getPeer() + public function getPeer(): ?string { return $this->stream->getPeer(); } @@ -107,7 +105,7 @@ public function getPeer() /** * {@inheritdoc} */ - public function cancel() + public function cancel(): void { $this->stream->cancel(); } @@ -115,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 033e2e92aa9c..8008b6edd237 100644 --- a/Gax/src/Transport/GrpcFallbackTransport.php +++ b/Gax/src/Transport/GrpcFallbackTransport.php @@ -1,4 +1,6 @@ null, @@ -103,7 +106,7 @@ public static function build(string $apiEndpoint, array $config = []) * @return never * @throws \BadMethodCallException */ - public function startServerStreamingCall(Call $call, array $options) + public function startServerStreamingCall(Call $call, array $options): never { $this->throwUnsupportedException(); } @@ -111,7 +114,7 @@ public function startServerStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function startUnaryCall(Call $call, array $options) + public function startUnaryCall(Call $call, array $options): PromiseInterface { $httpHandler = $this->httpHandler; @@ -143,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); @@ -169,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 */ @@ -182,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'] ?? []; @@ -211,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 cce4b4e7865a..de031f7d16e5 100644 --- a/Gax/src/Transport/GrpcTransport.php +++ b/Gax/src/Transport/GrpcTransport.php @@ -1,4 +1,6 @@ logger = $logger; + $this->logger = $logger ?: null; } /** @@ -114,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 += [ @@ -161,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); @@ -196,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); @@ -216,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); @@ -262,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'] ?? []; @@ -324,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'] ?? []; @@ -354,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 5e4bb242d23c..bde22e98091f 100644 --- a/Gax/src/Transport/HttpUnaryTransportTrait.php +++ b/Gax/src/Transport/HttpUnaryTransportTrait.php @@ -1,4 +1,6 @@ throwUnsupportedException(); } @@ -64,7 +68,7 @@ public function startClientStreamingCall(Call $call, array $options) * @return never * @throws \BadMethodCallException */ - public function startBidiStreamingCall(Call $call, array $options) + public function startBidiStreamingCall(Call $call, array $options): never { $this->throwUnsupportedException(); } @@ -72,7 +76,7 @@ public function startBidiStreamingCall(Call $call, array $options) /** * {@inheritdoc} */ - public function close() + public function close(): void { // Nothing to do. } @@ -81,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'] ?? []; @@ -117,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']; @@ -131,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; } @@ -140,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 90aba068034b..d0c186294af2 100644 --- a/Gax/src/Transport/Rest/JsonStreamDecoder.php +++ b/Gax/src/Transport/Rest/JsonStreamDecoder.php @@ -1,4 +1,6 @@ doDecode() as $response) { @@ -110,9 +113,9 @@ public function decode() } /** - * @return \Generator + * @return Generator */ - private function doDecode() + private function doDecode(): Generator { $decodeType = $this->decodeType; $str = false; @@ -230,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 92e1f2b1ffdd..b92cdb5ed45f 100644 --- a/Gax/src/Transport/Rest/RestServerStreamingCall.php +++ b/Gax/src/Transport/Rest/RestServerStreamingCall.php @@ -1,4 +1,6 @@ originalRequest = $this->appendHeaders($request, $headers); @@ -109,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) ? @@ -123,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.'); @@ -145,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; } @@ -156,7 +159,7 @@ public function getStatus() /** * {@inheritdoc} */ - public function getMetadata() + public function getMetadata(): ?array { return is_null($this->response) ? null : $this->response->getHeaders(); } @@ -165,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(); } @@ -173,15 +176,15 @@ public function getTrailingMetadata() /** * {@inheritdoc} */ - public function getPeer() + public function getPeer(): string { - return $this->originalRequest->getUri(); + return (string) $this->originalRequest->getUri(); } /** * {@inheritdoc} */ - public function cancel() + public function cancel(): void { if (isset($this->decoder)) { $this->decoder->close(); @@ -192,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 2ab582338320..31397e2d8a05 100644 --- a/Gax/src/Transport/RestTransport.php +++ b/Gax/src/Transport/RestTransport.php @@ -1,4 +1,6 @@ null, @@ -111,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); @@ -184,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) { @@ -228,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); } @@ -261,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, @@ -283,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 682a4301989c..9aaca0a147ed 100644 --- a/Gax/src/Transport/TransportInterface.php +++ b/Gax/src/Transport/TransportInterface.php @@ -1,4 +1,6 @@ assertEquals($expectedCredentialsWrapper, $actualCredentialsWrapper); } - - /** - * @dataProvider createCredentialsWrapperValidationExceptionData - */ - public function testCreateCredentialsWrapperValidationException($auth, $authConfig) + public function testCreateCredentialsWrapperValidationException() { - $this->expectException(ValidationException::class); $this->clientStub->createCredentialsWrapper( - $auth, - $authConfig, + 'not a json string', + [], '' ); } - public function createCredentialsWrapperValidationExceptionData() - { - return [ - ['not a json string', []], - [new \stdClass(), []], - ]; - } - - /** - * @dataProvider createCredentialsWrapperInvalidArgumentExceptionData - */ - public function testCreateCredentialsWrapperInvalidArgumentException($auth, $authConfig) + public function testCreateCredentialsWrapperInvalidArgumentException() { - - $this->expectException(InvalidArgumentException::class); + $this->expectException(\InvalidArgumentException::class); $this->clientStub->createCredentialsWrapper( - $auth, - $authConfig, + ['array' => 'without right keys'], + [], '' ); } - 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); } @@ -245,9 +217,7 @@ public function buildClientOptionsProvider() 'transport' => null, 'transportConfig' => [ 'grpc' => [ - 'stubOpts' => [ - 'grpc.service_config_disable_resolution' => 1, - ], + 'stubOpts' => ['grpc.service_config_disable_resolution' => 1], 'logger' => null, ], 'rest' => [ @@ -305,9 +275,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 d59536d84d6d..a4f69730f2a3 100644 --- a/Gax/tests/Unit/CredentialsWrapperTest.php +++ b/Gax/tests/Unit/CredentialsWrapperTest.php @@ -578,11 +578,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); } public function testInsecureCredentialsWrapperImplementsHeaderCredentialsInterface() diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index c2af15a60a2a..4a2803bfdd79 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -972,8 +972,11 @@ public function testBuildClientOptionsRegionalEndpoint(?string $apiEndpoint, ?st $client = new class() extends StubGapicClient { public array $capturedCredentialsConfig = []; - public function createCredentialsWrapper($credentials, array $credentialsConfig, string $universeDomain): HeaderCredentialsInterface - { + public function createCredentialsWrapper( + string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials, + array $credentialsConfig, + string $universeDomain + ): HeaderCredentialsInterface { $this->capturedCredentialsConfig = $credentialsConfig; return new InsecureCredentialsWrapper(); } @@ -1561,7 +1564,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); @@ -1579,7 +1582,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); @@ -1632,7 +1635,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); @@ -1650,7 +1653,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); @@ -1702,7 +1705,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); @@ -1720,7 +1723,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); @@ -1913,8 +1916,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; @@ -1927,12 +1937,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; } }; 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/OperationResponseTest.php b/Gax/tests/Unit/OperationResponseTest.php index 4ef50bb3ac77..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); @@ -527,7 +506,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 +517,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/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/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; + } } 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 @@ willReturn($this->operationResponse->reveal()); new OperationResponse('my-operation', new DatabaseAdminClient([ - 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE() + 'credentials' => new InsecureCredentialsWrapper() ]), [ 'lastProtoResponse' => $this->serializer->decodeMessage( new DatabaseProto(),