diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 6c1ce8191292..13bd49d06607 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -36,6 +36,7 @@ Update your `google/gax` dependency to `^2.0`: - **`CredentialsWrapper::getBearerString()`**: Removed. Use `CredentialsWrapper::getAuthorizationHeaderCallback()` instead. - **`ClientOptionsTrait::initGrpcGcpConfig()`**: Removed. +- **`ClientOptionsTrait::modifyClientOptions()`**: Removed. Instead of mutating the options array in `modifyClientOptions()`, use `ClientOptions::fromArray(array $options): ClientOptions` (or pass a `Google\ApiCore\Options\ClientOptions` instance directly), configure options via fluent setters/getters on `ClientOptions`, and pass the `ClientOptions` instance to `buildClientOptions()` / `setClientOptions()`. - **`HttpUnaryTransportTrait::startServerStreamingCall()`**: Removed (along with the `unsupportedServerStreamingCall` trait alias on `RestTransport`). - **V1 GAPIC surface backwards-compatibility mode**: - Removed `GapicClientTrait::$backwardsCompatibilityMode` and `GapicClientTrait::isBackwardsCompatibilityMode()`. diff --git a/Gax/src/ClientOptionsTrait.php b/Gax/src/ClientOptionsTrait.php index af368900c690..8fa4adac6cc2 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -53,6 +53,7 @@ trait ClientOptionsTrait use ArrayTrait; private static ?string $gapicVersionFromFile = null; + private ?ClientOptions $clientOptions = null; private static function getGapicVersion(array $options): string { @@ -92,7 +93,20 @@ private static function getClientDefaults() private function buildClientOptions(array|ClientOptions $options): array { if ($options instanceof ClientOptions) { - $options = $options->toArray(); + $this->clientOptions = clone $options; + $options = array_filter( + $options->toArray(), + fn ($v) => $v !== null && $v !== [] + ); + if (isset($options['transportConfig'])) { + foreach ($options['transportConfig'] as $transport => $config) { + $options['transportConfig'][$transport] = array_filter( + $config, + fn ($v) => $v !== null && $v !== [] + ); + } + $options['transportConfig'] = array_filter($options['transportConfig']); + } } // Build $defaultOptions starting from top level @@ -175,13 +189,6 @@ private function buildClientOptions(array|ClientOptions $options): array $options['transportConfig']['grpc-fallback']['logger'] = $options['logger'] ?? null; } - $preModifiedOptions = $options; - $this->modifyClientOptions($options); - // NOTE: this is required to ensure backwards compatiblity with $options['apiEndpoint'] - if ($options['apiEndpoint'] !== $preModifiedOptions['apiEndpoint']) { - $apiEndpoint = $options['apiEndpoint']; - } - // serviceAddress is now deprecated and acts as an alias for apiEndpoint if (isset($options['serviceAddress'])) { $apiEndpoint = $this->pluck('serviceAddress', $options, false); @@ -241,6 +248,31 @@ private function buildClientOptions(array|ClientOptions $options): array return $options; } + /** + * Get the resolved ClientOptions for the client. This method is protected to support + * use by customized clients. + * + * @access private + * @return ?ClientOptions + */ + protected function getClientOptions(): ?ClientOptions + { + return $this->clientOptions; + } + + /** + * Create the ClientOptions instance for the client. Customized clients may override + * this method to return a ClientOptions subclass. + * + * @param array $options + * @access private + * @return ClientOptions + */ + protected function createClientOptions(array $options): ClientOptions + { + return new ClientOptions($options); + } + private function shouldUseMtlsEndpoint(array $options): bool { $mtlsEndpointEnvVar = getenv('GOOGLE_API_USE_MTLS_ENDPOINT'); @@ -300,23 +332,6 @@ private static function supportedTransports(): array return ['grpc', 'grpc-fallback', 'rest']; } - // Gapic Client Extension Points - // The methods below provide extension points that can be used to customize client - // functionality. These extension points are currently considered - // private and may change at any time. - - /** - * Modify options passed to the client before calling setClientOptions. - * - * @param array $options - * @access private - * @internal - */ - protected function modifyClientOptions(array &$options) - { - // Do nothing - this method exists to allow option modification by partial veneers. - } - /** * @param null|false|LoggerInterface $logger * @param string $options diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index d1f24bdda0d6..46a0e2e3578c 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -211,9 +211,9 @@ protected function getCredentialsWrapper(): ?HeaderCredentialsInterface } /** - * Configures the GAPIC client based on an array of options. + * Configures the GAPIC client based on an array or ClientOptions instance. * - * @param array $options { + * @param array|ClientOptions $options { * An array of required and optional arguments. * * @type string $apiEndpoint @@ -273,13 +273,19 @@ protected function getCredentialsWrapper(): ?HeaderCredentialsInterface * } * @throws ValidationException */ - private function setClientOptions(array $options): void + private function setClientOptions(array|ClientOptions $options): void { + if ($options instanceof ClientOptions) { + $this->clientOptions = clone $options; + $optionsArray = $options->toArray(); + } else { + $optionsArray = $options; + } // serviceAddress is now deprecated and acts as an alias for apiEndpoint - if (isset($options['serviceAddress'])) { - $options['apiEndpoint'] = $this->pluck('serviceAddress', $options, false); + if (isset($optionsArray['serviceAddress'])) { + $optionsArray['apiEndpoint'] = $this->pluck('serviceAddress', $optionsArray, false); } - self::validateNotNull($options, [ + self::validateNotNull($optionsArray, [ 'apiEndpoint', 'serviceName', 'descriptorsConfigPath', @@ -288,7 +294,7 @@ private function setClientOptions(array $options): void 'credentialsConfig', 'transportConfig', ]); - self::traitValidate($options, [ + self::traitValidate($optionsArray, [ 'credentials', 'transport', 'gapicVersion', @@ -296,12 +302,12 @@ private function setClientOptions(array $options): void 'libVersion', ]); - // "hasEmulator" is not a supported Client Option, but is used - // internally to determine if the client is running in emulator mode. - // Therefore, we need to remove it from the $options array before - // creating the ClientOptions. - $hasEmulator = $this->pluck('hasEmulator', $options, false) ?? false; - $options = new ClientOptions($options); + $hasEmulator = (bool) ($optionsArray['hasEmulator'] ?? false); + if ($this->clientOptions instanceof ClientOptions) { + $options = $this->clientOptions->fromArray($optionsArray); + } else { + $options = $this->clientOptions = $this->createClientOptions($optionsArray); + } $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( $this->serviceName, @@ -451,6 +457,9 @@ private function createOperationsClient(array $options) if (isset($options['operationsClient'])) { return $options['operationsClient']; } + if (isset($this->clientOptions['operationsClient'])) { + return $this->clientOptions['operationsClient']; + } return new OperationsClient($options); } diff --git a/Gax/src/Options/CallOptions.php b/Gax/src/Options/CallOptions.php index 1df2088183a2..060856d1e1dc 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -76,7 +76,7 @@ class CallOptions implements ArrayAccess, OptionsInterface * that object will be used instead of the method defaults. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } @@ -98,8 +98,10 @@ private function fromArray(array $arr): void /** * @param array $headers + * + * @return static */ - public function setHeaders(array $headers): self + public function setHeaders(array $headers): static { $this->headers = $headers; @@ -108,8 +110,10 @@ public function setHeaders(array $headers): self /** * @param int|null $timeoutMillis + * + * @return static */ - public function setTimeoutMillis(?int $timeoutMillis): self + public function setTimeoutMillis(?int $timeoutMillis): static { $this->timeoutMillis = $timeoutMillis; @@ -134,8 +138,10 @@ public function setTimeoutMillis(?int $timeoutMillis): self * callable. By default these are passed to {@see \GuzzleHttp\Client} as request options. * See {@link https://docs.guzzlephp.org/en/stable/request-options.html}. * } + * + * @return static */ - public function setTransportOptions(array $transportOptions): self + public function setTransportOptions(array $transportOptions): static { $this->transportOptions = $transportOptions; @@ -145,9 +151,9 @@ public function setTransportOptions(array $transportOptions): self /** * @param RetrySettings|array|null $retrySettings * - * @return $this + * @return static */ - public function setRetrySettings(RetrySettings|array|null $retrySettings): self + public function setRetrySettings(RetrySettings|array|null $retrySettings): static { $this->retrySettings = $retrySettings; @@ -157,16 +163,19 @@ public function setRetrySettings(RetrySettings|array|null $retrySettings): self /** * @param array|null $middlewareOptions * - * @return $this + * @return static */ - public function setMiddlewareOptions(array|null $middlewareOptions): self + public function setMiddlewareOptions(array|null $middlewareOptions): static { $this->middlewareOptions = $middlewareOptions; return $this; } - public function setMetadataCallback(callable|null $metadataCallback): self + /** + * @return static + */ + public function setMetadataCallback(callable|null $metadataCallback): static { $this->metadataCallback = $metadataCallback; diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 66ea4affe48a..8a436e43fb1f 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -43,18 +43,15 @@ /** * The ClientOptions class adds typing to the associative array of options - * passed into each API client constructor. To use this class directly, pass - * the result of {@see \Google\ApiCore\Options\ClientOptions::toArray()} to the - * client constructor: + * passed into each API client constructor: * * ``` * use Google\ApiCore\Options\ClientOptions; - * use Google\Cloud\SecretManager\Client\SecretManagerClient; + * use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient; * - * $options = new ClientOptions([ - * 'apiEndpoint' => 'my-custom-endpoint.com' - * ]); - * $secretManager = new SecretManagerClient($options->toArray()); + * $options = (new ClientOptions()) + * ->setApiEndpoint('my-custom-endpoint.com'); + * $secretManager = new SecretManagerServiceClient($options); * ``` * * Note: It's possible to pass an associative array to the API clients as well, @@ -64,39 +61,39 @@ class ClientOptions implements ArrayAccess, OptionsInterface { use OptionsTrait; - private ?string $apiEndpoint; + protected ?string $apiEndpoint = null; - private bool $disableRetries; + protected bool $disableRetries = false; - private array $clientConfig; + protected array $clientConfig = []; - private string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials; + protected string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials = null; - private array $credentialsConfig; + protected array $credentialsConfig = []; - private string|TransportInterface|null $transport; + protected string|TransportInterface|null $transport = null; - private TransportOptions $transportConfig; + protected TransportOptions $transportConfig; - private ?string $versionFile; + protected ?string $versionFile = null; - private ?string $descriptorsConfigPath; + protected ?string $descriptorsConfigPath = null; - private ?string $serviceName; + protected ?string $serviceName = null; - private ?string $libName; + protected ?string $libName = null; - private ?string $libVersion; + protected ?string $libVersion = null; - private ?string $gapicVersion; + protected ?string $gapicVersion = null; - private ?Closure $clientCertSource; + protected ?Closure $clientCertSource = null; - private ?string $universeDomain; + protected ?string $universeDomain = null; - private ?string $apiKey; + protected ?string $apiKey = null; - private null|false|LoggerInterface $logger; + protected null|false|LoggerInterface $logger = null; /** * @param array $options { @@ -170,55 +167,77 @@ class ClientOptions implements ArrayAccess, OptionsInterface * A PSR-3 compliant logger. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } + public function __clone(): void + { + if (isset($this->transportConfig)) { + $this->transportConfig = clone $this->transportConfig; + } + } + /** - * Sets the array of options as class properites. + * Sets the array of options as class properties. * * @param array $arr See the constructor for the list of supported options. + * + * @return static */ - private function fromArray(array $arr): void + public function fromArray(array $arr): static { - $this->setApiEndpoint($arr['apiEndpoint'] ?? null); - $this->setDisableRetries($arr['disableRetries'] ?? false); - $this->setClientConfig($arr['clientConfig'] ?? []); - $this->setCredentials($arr['credentials'] ?? null); - $this->setCredentialsConfig($arr['credentialsConfig'] ?? []); - $this->setTransport($arr['transport'] ?? null); - $this->setTransportConfig(new TransportOptions($arr['transportConfig'] ?? [])); - $this->setVersionFile($arr['versionFile'] ?? null); - $this->setDescriptorsConfigPath($arr['descriptorsConfigPath'] ?? null); - $this->setServiceName($arr['serviceName'] ?? null); - $this->setLibName($arr['libName'] ?? null); - $this->setLibVersion($arr['libVersion'] ?? null); - $this->setGapicVersion($arr['gapicVersion'] ?? null); - $this->setClientCertSource($arr['clientCertSource'] ?? null); - $this->setUniverseDomain($arr['universeDomain'] ?? null); - $this->setApiKey($arr['apiKey'] ?? null); - $this->setLogger($arr['logger'] ?? null); + $this->setApiEndpoint($arr['serviceAddress'] ?? $arr['apiEndpoint'] ?? $this->apiEndpoint); + $this->setDisableRetries($arr['disableRetries'] ?? $this->disableRetries); + $this->setClientConfig($arr['clientConfig'] ?? $this->clientConfig); + $this->setCredentials($arr['credentials'] ?? $this->credentials); + $this->setCredentialsConfig($arr['credentialsConfig'] ?? $this->credentialsConfig); + $this->setTransport($arr['transport'] ?? $this->transport); + $this->setTransportConfig($arr['transportConfig'] ?? $this->transportConfig ?? []); + $this->setVersionFile($arr['versionFile'] ?? $this->versionFile); + $this->setDescriptorsConfigPath($arr['descriptorsConfigPath'] ?? $this->descriptorsConfigPath); + $this->setServiceName($arr['serviceName'] ?? $this->serviceName); + $this->setLibName($arr['libName'] ?? $this->libName); + $this->setLibVersion($arr['libVersion'] ?? $this->libVersion); + $this->setGapicVersion($arr['gapicVersion'] ?? $this->gapicVersion); + $this->setClientCertSource($arr['clientCertSource'] ?? $this->clientCertSource); + $this->setUniverseDomain($arr['universeDomain'] ?? $this->universeDomain); + $this->setApiKey($arr['apiKey'] ?? $this->apiKey); + $this->setLogger($arr['logger'] ?? $this->logger); + + return $this; } /** * @param ?string $apiEndpoint * - * @return $this + * @return static */ - public function setApiEndpoint(?string $apiEndpoint): self + public function setApiEndpoint(?string $apiEndpoint): static { $this->apiEndpoint = $apiEndpoint; return $this; } + /** + * @deprecated Use {@see ClientOptions::setApiEndpoint()} instead. + * @param ?string $serviceAddress + * + * @return static + */ + public function setServiceAddress(?string $serviceAddress): static + { + return $this->setApiEndpoint($serviceAddress); + } + /** * @param bool $disableRetries * - * @return $this + * @return static */ - public function setDisableRetries(bool $disableRetries): self + public function setDisableRetries(bool $disableRetries): static { $this->disableRetries = $disableRetries; @@ -228,9 +247,9 @@ public function setDisableRetries(bool $disableRetries): self /** * @param string|array $clientConfig * - * @return $this + * @return static */ - public function setClientConfig(string|array $clientConfig): self + public function setClientConfig(string|array $clientConfig): static { if (is_string($clientConfig)) { $this->clientConfig = json_decode(file_get_contents($clientConfig), true); @@ -244,11 +263,11 @@ public function setClientConfig(string|array $clientConfig): self /** * @param string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials * - * @return $this + * @return static */ public function setCredentials( string|array|FetchAuthTokenInterface|HeaderCredentialsInterface|null $credentials - ): self { + ): static { $this->credentials = $credentials; return $this; @@ -257,9 +276,9 @@ public function setCredentials( /** * @param array $credentialsConfig * - * @return $this + * @return static */ - public function setCredentialsConfig(array $credentialsConfig): self + public function setCredentialsConfig(array $credentialsConfig): static { $this->credentialsConfig = $credentialsConfig; @@ -269,9 +288,9 @@ public function setCredentialsConfig(array $credentialsConfig): self /** * @param string|TransportInterface|null $transport * - * @return $this + * @return static */ - public function setTransport(string|TransportInterface|null $transport): self + public function setTransport(string|TransportInterface|null $transport): static { $this->transport = $transport; @@ -279,12 +298,15 @@ public function setTransport(string|TransportInterface|null $transport): self } /** - * @param TransportOptions $transportConfig + * @param TransportOptions|array $transportConfig * - * @return $this + * @return static */ - public function setTransportConfig(TransportOptions $transportConfig): self + public function setTransportConfig(TransportOptions|array $transportConfig): static { + if (is_array($transportConfig)) { + $transportConfig = new TransportOptions($transportConfig); + } $this->transportConfig = $transportConfig; return $this; @@ -293,9 +315,9 @@ public function setTransportConfig(TransportOptions $transportConfig): self /** * @param ?string $versionFile * - * @return $this + * @return static */ - public function setVersionFile(?string $versionFile): self + public function setVersionFile(?string $versionFile): static { $this->versionFile = $versionFile; @@ -305,9 +327,9 @@ public function setVersionFile(?string $versionFile): self /** * @param ?string $descriptorsConfigPath * - * @return $this + * @return static */ - private function setDescriptorsConfigPath(?string $descriptorsConfigPath): self + public function setDescriptorsConfigPath(?string $descriptorsConfigPath): static { if (!is_null($descriptorsConfigPath)) { self::validateFileExists($descriptorsConfigPath); @@ -320,9 +342,9 @@ private function setDescriptorsConfigPath(?string $descriptorsConfigPath): self /** * @param ?string $serviceName * - * @return $this + * @return static */ - public function setServiceName(?string $serviceName): self + public function setServiceName(?string $serviceName): static { $this->serviceName = $serviceName; @@ -332,9 +354,9 @@ public function setServiceName(?string $serviceName): self /** * @param ?string $libName * - * @return $this + * @return static */ - public function setLibName(?string $libName): self + public function setLibName(?string $libName): static { $this->libName = $libName; @@ -344,9 +366,9 @@ public function setLibName(?string $libName): self /** * @param ?string $libVersion * - * @return $this + * @return static */ - public function setLibVersion(?string $libVersion): self + public function setLibVersion(?string $libVersion): static { $this->libVersion = $libVersion; @@ -356,9 +378,9 @@ public function setLibVersion(?string $libVersion): self /** * @param ?string $gapicVersion * - * @return $this + * @return static */ - public function setGapicVersion(?string $gapicVersion): self + public function setGapicVersion(?string $gapicVersion): static { $this->gapicVersion = $gapicVersion; @@ -368,9 +390,9 @@ public function setGapicVersion(?string $gapicVersion): self /** * @param ?callable $clientCertSource * - * @return $this + * @return static */ - public function setClientCertSource(?callable $clientCertSource): self + public function setClientCertSource(?callable $clientCertSource): static { if (!is_null($clientCertSource)) { $clientCertSource = Closure::fromCallable($clientCertSource); @@ -381,11 +403,11 @@ public function setClientCertSource(?callable $clientCertSource): self } /** - * @param string $universeDomain + * @param ?string $universeDomain * - * @return $this + * @return static */ - public function setUniverseDomain(?string $universeDomain): self + public function setUniverseDomain(?string $universeDomain): static { $this->universeDomain = $universeDomain; @@ -393,11 +415,11 @@ public function setUniverseDomain(?string $universeDomain): self } /** - * @param string $apiKey + * @param ?string $apiKey * - * @return $this + * @return static */ - public function setApiKey(?string $apiKey): self + public function setApiKey(?string $apiKey): static { $this->apiKey = $apiKey; @@ -407,9 +429,9 @@ public function setApiKey(?string $apiKey): self /** * @param null|false|LoggerInterface $logger * - * @return $this + * @return static */ - public function setLogger(null|false|LoggerInterface $logger): self + public function setLogger(null|false|LoggerInterface $logger): static { $this->logger = $logger; diff --git a/Gax/src/Options/OptionsTrait.php b/Gax/src/Options/OptionsTrait.php index 444027c66190..865a5f10d2d2 100644 --- a/Gax/src/Options/OptionsTrait.php +++ b/Gax/src/Options/OptionsTrait.php @@ -47,7 +47,7 @@ trait OptionsTrait * @param string $filePath * @throws ValidationException */ - private static function validateFileExists(string $filePath) + protected static function validateFileExists(string $filePath) { if (!file_exists($filePath)) { throw new ValidationException("Could not find specified file: $filePath"); @@ -65,7 +65,7 @@ public function offsetExists($offset): bool #[\ReturnTypeWillChange] public function offsetGet($offset) { - return $this->$offset; + return $this->$offset ?? null; } /** diff --git a/Gax/src/Options/TransportOptions.php b/Gax/src/Options/TransportOptions.php index af8fa3994d44..57db42eb345e 100644 --- a/Gax/src/Options/TransportOptions.php +++ b/Gax/src/Options/TransportOptions.php @@ -43,11 +43,11 @@ class TransportOptions implements ArrayAccess, OptionsInterface { use OptionsTrait; - private GrpcTransportOptions $grpc; + protected GrpcTransportOptions $grpc; - private GrpcFallbackTransportOptions $grpcFallback; + protected GrpcFallbackTransportOptions $grpcFallback; - private RestTransportOptions $rest; + protected RestTransportOptions $rest; /** * @param array $options { @@ -58,56 +58,101 @@ class TransportOptions implements ArrayAccess, OptionsInterface * @type array $rest * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } + public function __clone(): void + { + $this->grpc = clone $this->grpc; + $this->grpcFallback = clone $this->grpcFallback; + $this->rest = clone $this->rest; + } + /** - * Sets the array of options as class properites. + * Sets the array of options as class properties. * * @param array $arr See the constructor for the list of supported options. */ - private function fromArray(array $arr): void + protected function fromArray(array $arr): void { - $this->setGrpc(new GrpcTransportOptions($arr['grpc'] ?? [])); - $this->setGrpcFallback(new GrpcFallbackTransportOptions($arr['grpc-fallback'] ?? [])); - $this->setRest(new RestTransportOptions($arr['rest'] ?? [])); + $this->setGrpc($arr['grpc'] ?? []); + $this->setGrpcFallback($arr['grpc-fallback'] ?? $arr['grpcFallback'] ?? []); + $this->setRest($arr['rest'] ?? []); } /** - * @param GrpcTransportOptions $grpc + * @param GrpcTransportOptions|array $grpc * - * @return $this + * @return static */ - public function setGrpc(GrpcTransportOptions $grpc): self + public function setGrpc(GrpcTransportOptions|array $grpc): static { + if (is_array($grpc)) { + $grpc = new GrpcTransportOptions($grpc); + } $this->grpc = $grpc; return $this; } /** - * @param GrpcFallbackTransportOptions $grpcFallback + * @param GrpcFallbackTransportOptions|array $grpcFallback * - * @return $this + * @return static */ - public function setGrpcFallback(GrpcFallbackTransportOptions $grpcFallback): self + public function setGrpcFallback(GrpcFallbackTransportOptions|array $grpcFallback): static { + if (is_array($grpcFallback)) { + $grpcFallback = new GrpcFallbackTransportOptions($grpcFallback); + } $this->grpcFallback = $grpcFallback; return $this; } /** - * @param RestTransportOptions $rest + * @param RestTransportOptions|array $rest * - * @return $this + * @return static */ - public function setRest(RestTransportOptions $rest): self + public function setRest(RestTransportOptions|array $rest): static { + if (is_array($rest)) { + $rest = new RestTransportOptions($rest); + } $this->rest = $rest; return $this; } + + public function offsetExists($offset): bool + { + if ($offset === 'grpc-fallback') { + $offset = 'grpcFallback'; + } + return isset($this->$offset); + } + + /** + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + if ($offset === 'grpc-fallback') { + $offset = 'grpcFallback'; + } + return $this->$offset ?? null; + } + + public function toArray(): array + { + return [ + 'grpc' => $this->grpc->toArray(), + 'grpc-fallback' => $this->grpcFallback->toArray(), + 'rest' => $this->rest->toArray(), + ]; + } } diff --git a/Gax/src/Options/TransportOptions/GrpcFallbackTransportOptions.php b/Gax/src/Options/TransportOptions/GrpcFallbackTransportOptions.php index c5ad5ea40648..86d66f47d7f7 100644 --- a/Gax/src/Options/TransportOptions/GrpcFallbackTransportOptions.php +++ b/Gax/src/Options/TransportOptions/GrpcFallbackTransportOptions.php @@ -66,7 +66,7 @@ class GrpcFallbackTransportOptions implements ArrayAccess, OptionsInterface * A PSR-3 logger interface instance. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } @@ -86,9 +86,9 @@ private function fromArray(array $arr): void /** * @param ?callable $httpHandler * - * @return $this + * @return static */ - public function setHttpHandler(?callable $httpHandler): self + public function setHttpHandler(?callable $httpHandler): static { if (!is_null($httpHandler)) { $httpHandler = Closure::fromCallable($httpHandler); @@ -101,9 +101,9 @@ public function setHttpHandler(?callable $httpHandler): self /** * @param ?callable $clientCertSource * - * @return $this + * @return static */ - public function setClientCertSource(?callable $clientCertSource): self + public function setClientCertSource(?callable $clientCertSource): static { if (!is_null($clientCertSource)) { $clientCertSource = Closure::fromCallable($clientCertSource); @@ -116,9 +116,9 @@ public function setClientCertSource(?callable $clientCertSource): self /** * @param null|false|LoggerInterface $logger * - * @return $this + * @return static */ - public function setLogger(null|false|LoggerInterface $logger): self + public function setLogger(null|false|LoggerInterface $logger): static { $this->logger = $logger; diff --git a/Gax/src/Options/TransportOptions/GrpcTransportOptions.php b/Gax/src/Options/TransportOptions/GrpcTransportOptions.php index 5708cf0853e3..571cd75fa686 100644 --- a/Gax/src/Options/TransportOptions/GrpcTransportOptions.php +++ b/Gax/src/Options/TransportOptions/GrpcTransportOptions.php @@ -76,7 +76,7 @@ class GrpcTransportOptions implements ArrayAccess, OptionsInterface * @type null|false|LoggerInterface A PSR-3 Logger Interface. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } @@ -98,9 +98,9 @@ private function fromArray(array $arr): void /** * @param array $stubOpts * - * @return $this + * @return static */ - public function setStubOpts(array $stubOpts): self + public function setStubOpts(array $stubOpts): static { $this->stubOpts = $stubOpts; @@ -110,9 +110,9 @@ public function setStubOpts(array $stubOpts): self /** * @param ?Channel $channel * - * @return $this + * @return static */ - public function setChannel(?Channel $channel): self + public function setChannel(?Channel $channel): static { $this->channel = $channel; @@ -122,9 +122,9 @@ public function setChannel(?Channel $channel): self /** * @param Interceptor[] $interceptors * - * @return $this + * @return static */ - public function setInterceptors(array $interceptors): self + public function setInterceptors(array $interceptors): static { $this->interceptors = $interceptors; @@ -134,9 +134,9 @@ public function setInterceptors(array $interceptors): self /** * @param ?callable $clientCertSource * - * @return $this + * @return static */ - public function setClientCertSource(?callable $clientCertSource): self + public function setClientCertSource(?callable $clientCertSource): static { if (!is_null($clientCertSource)) { $clientCertSource = Closure::fromCallable($clientCertSource); @@ -149,9 +149,9 @@ public function setClientCertSource(?callable $clientCertSource): self /** * @param null|false|LoggerInterface $logger * - * @return $this + * @return static */ - public function setLogger(null|false|LoggerInterface $logger): self + public function setLogger(null|false|LoggerInterface $logger): static { $this->logger = $logger; diff --git a/Gax/src/Options/TransportOptions/RestTransportOptions.php b/Gax/src/Options/TransportOptions/RestTransportOptions.php index 53b6f3c891f2..a6d6b3cacf92 100644 --- a/Gax/src/Options/TransportOptions/RestTransportOptions.php +++ b/Gax/src/Options/TransportOptions/RestTransportOptions.php @@ -70,7 +70,7 @@ class RestTransportOptions implements ArrayAccess, OptionsInterface * A PSR-3 compliant logger instance. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } @@ -91,9 +91,9 @@ private function fromArray(array $arr): void /** * @param ?callable $httpHandler * - * @return $this + * @return static */ - public function setHttpHandler(?callable $httpHandler): self + public function setHttpHandler(?callable $httpHandler): static { if (!is_null($httpHandler)) { $httpHandler = Closure::fromCallable($httpHandler); @@ -106,9 +106,9 @@ public function setHttpHandler(?callable $httpHandler): self /** * @param ?callable $clientCertSource * - * @return $this + * @return static */ - public function setClientCertSource(?callable $clientCertSource): self + public function setClientCertSource(?callable $clientCertSource): static { if (!is_null($clientCertSource)) { $clientCertSource = Closure::fromCallable($clientCertSource); @@ -121,9 +121,9 @@ public function setClientCertSource(?callable $clientCertSource): self /** * @param ?string $restClientConfigPath * - * @return $this + * @return static */ - public function setRestClientConfigPath(?string $restClientConfigPath): self + public function setRestClientConfigPath(?string $restClientConfigPath): static { $this->restClientConfigPath = $restClientConfigPath; @@ -133,9 +133,9 @@ public function setRestClientConfigPath(?string $restClientConfigPath): self /** * @param null|false|LoggerInterface $logger * - * @return $this + * @return static */ - public function setLogger(null|false|LoggerInterface $logger): self + public function setLogger(null|false|LoggerInterface $logger): static { $this->logger = $logger; diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 4a2803bfdd79..79b83952fa3f 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1102,16 +1102,50 @@ public function testServiceAddressOption() $this->assertArrayNotHasKey('serviceAddress', $updatedOptions); } - public function testModifyClientOptions() + public function testExtendedClientOptions() + { + $customOptionsClass = new class() extends \Google\ApiCore\Options\ClientOptions { + protected ?string $developerToken = null; + + public function setDeveloperToken(?string $developerToken): static + { + $this->developerToken = $developerToken; + return $this; + } + + public function getDeveloperToken(): ?string + { + return $this->developerToken; + } + }; + + $options = (new ($customOptionsClass::class)()) + ->setDisableRetries(true) + ->setApiEndpoint('abc123') + ->setDeveloperToken('dev-token-123'); + + $client = new GapicV2SurfaceClient($options); + $resolvedOptions = $client->getClientOptions(); + + $this->assertInstanceOf($customOptionsClass::class, $resolvedOptions); + $this->assertNotSame($options, $resolvedOptions); + $this->assertSame('dev-token-123', $resolvedOptions->getDeveloperToken()); + $this->assertTrue($resolvedOptions['disableRetries']); + $this->assertEquals('abc123', $resolvedOptions['apiEndpoint']); + $this->assertEquals('test.interface.v1.api', $resolvedOptions['serviceName']); + } + + public function testCreateClientOptionsOverride() { - $options = []; $client = new StubGapicClientExtension(); - $updatedOptions = $client->buildClientOptions($options); + $updatedOptions = $client->buildClientOptions([ + 'developer-token' => 'dev-token-456', + ]); $client->setClientOptions($updatedOptions); - $this->assertArrayHasKey('addNewOption', $updatedOptions); - $this->assertTrue($updatedOptions['disableRetries']); - $this->assertEquals('abc123', $updatedOptions['apiEndpoint']); + $resolvedOptions = $client->getClientOptions(); + $this->assertInstanceOf(StubCustomClientOptions::class, $resolvedOptions); + $this->assertSame('dev-token-456', $resolvedOptions->getDeveloperToken()); } private function buildClientToTestModifyCallMethods($clientClass = null) @@ -2076,6 +2110,7 @@ class StubGapicClient createOperationsClient as public; createTransport as public; determineMtlsEndpoint as public; + getClientOptions as public; getGapicVersion as public; getCredentialsWrapper as public; getPagedListResponse as public; @@ -2146,13 +2181,35 @@ public function get($name) } } +class StubCustomClientOptions extends \Google\ApiCore\Options\ClientOptions +{ + protected ?string $developerToken = null; + + public function fromArray(array $arr): static + { + parent::fromArray($arr); + $this->setDeveloperToken($arr['developer-token'] ?? $this->developerToken); + + return $this; + } + + public function setDeveloperToken(?string $developerToken): static + { + $this->developerToken = $developerToken; + return $this; + } + + public function getDeveloperToken(): ?string + { + return $this->developerToken; + } +} + class StubGapicClientExtension extends StubGapicClient { - protected function modifyClientOptions(array &$options) + protected function createClientOptions(array $options): \Google\ApiCore\Options\ClientOptions { - $options['disableRetries'] = true; - $options['addNewOption'] = true; - $options['apiEndpoint'] = 'abc123'; + return new StubCustomClientOptions($options); } protected function modifyUnaryCallable(callable &$callable) @@ -2257,6 +2314,7 @@ public function getOperation($request) class GapicV2SurfaceClient implements ServiceInterface, LongRunningOperationProviderInterface, IamProviderInterface { use GapicClientTrait { + getClientOptions as public; startCall as public; } use GapicClientStubTrait; @@ -2267,7 +2325,7 @@ class GapicV2SurfaceClient implements ServiceInterface, LongRunningOperationProv public static array $serviceScopes = []; private OperationsClient $operationsClient; - public function __construct(array $options = []) + public function __construct(array|\Google\ApiCore\Options\ClientOptions $options = []) { $clientOptions = $this->buildClientOptions($options); $this->setClientOptions($clientOptions); diff --git a/Gax/tests/Unit/Options/ClientOptionsTest.php b/Gax/tests/Unit/Options/ClientOptionsTest.php new file mode 100644 index 000000000000..9b4b6ad0a756 --- /dev/null +++ b/Gax/tests/Unit/Options/ClientOptionsTest.php @@ -0,0 +1,147 @@ +setApiEndpoint('custom.endpoint:443') + ->setDisableRetries(true) + ->setUniverseDomain('custom.domain') + ->setApiKey('my-api-key') + ->setTransportConfig([ + 'grpc' => ['stubOpts' => ['foo' => 'bar']], + 'grpc-fallback' => ['httpHandler' => fn () => null], + ]); + + $this->assertEquals('custom.endpoint:443', $options['apiEndpoint']); + $this->assertTrue($options['disableRetries']); + $this->assertEquals('custom.domain', $options['universeDomain']); + $this->assertEquals('my-api-key', $options['apiKey']); + $this->assertEquals(['foo' => 'bar'], $options['transportConfig']['grpc']['stubOpts']); + $this->assertNotNull($options['transportConfig']['grpc-fallback']['httpHandler']); + } + + public function testServiceAddressAlias() + { + $options = new ClientOptions([ + 'apiEndpoint' => 'default.endpoint:443', + 'serviceAddress' => 'override.endpoint:443', + ]); + $this->assertEquals('override.endpoint:443', $options['apiEndpoint']); + $this->assertArrayNotHasKey('serviceAddress', $options->toArray()); + + $fluid = (new ClientOptions())->setServiceAddress('fluid.endpoint:443'); + $this->assertEquals('fluid.endpoint:443', $fluid['apiEndpoint']); + } + + public function testSubclassClientOptions() + { + $options = new class([ + 'apiEndpoint' => 'ads.googleapis.com:443', + 'developer-token' => 'dev-123', + ]) extends ClientOptions { + protected ?string $developerToken = null; + protected ?string $loginCustomerId = null; + + public function fromArray(array $arr): static + { + parent::fromArray($arr); + $this->setDeveloperToken($arr['developer-token'] ?? $this->developerToken); + $this->setLoginCustomerId($arr['login-customer-id'] ?? $this->loginCustomerId); + + return $this; + } + + public function setDeveloperToken(?string $developerToken): static + { + $this->developerToken = $developerToken; + return $this; + } + + public function getDeveloperToken(): ?string + { + return $this->developerToken; + } + + public function setLoginCustomerId(?string $loginCustomerId): static + { + $this->loginCustomerId = $loginCustomerId; + return $this; + } + }; + + $options + ->setDisableRetries(true) + ->setLoginCustomerId('cust-456'); + + $this->assertEquals('ads.googleapis.com:443', $options['apiEndpoint']); + $this->assertTrue($options['disableRetries']); + $this->assertEquals('dev-123', $options->getDeveloperToken()); + $this->assertEquals('dev-123', $options['developerToken']); + $this->assertEquals('cust-456', $options['loginCustomerId']); + + $arr = $options->toArray(); + $this->assertEquals('dev-123', $arr['developerToken']); + $this->assertEquals('cust-456', $arr['loginCustomerId']); + } + + public function testArrayAccessSetThrowsException() + { + $this->expectException(BadMethodCallException::class); + + $options = new ClientOptions(); + $options['apiEndpoint'] = 'localhost:8086'; + } + + public function testCloneDeepCopiesTransportConfig() + { + $options = new ClientOptions([ + 'transportConfig' => [ + 'grpc' => ['stubOpts' => ['foo' => 'bar']], + ], + ]); + + $cloned = clone $options; + $cloned['transportConfig']['grpc']->setStubOpts(['foo' => 'baz']); + + $this->assertEquals(['foo' => 'bar'], $options['transportConfig']['grpc']['stubOpts']); + $this->assertEquals(['foo' => 'baz'], $cloned['transportConfig']['grpc']['stubOpts']); + } +}