From 543f383c1e680c66bcd2a4d2e607424396638ef3 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 17:20:53 +0000 Subject: [PATCH 1/6] feat(Gax)!: make ClientOptions extensible and fluid, remove modifyClientOptions --- Gax/MIGRATING.md | 1 + Gax/src/ClientOptionsTrait.php | 65 +++-- Gax/src/GapicClientTrait.php | 37 +-- Gax/src/Options/CallOptions.php | 32 ++- Gax/src/Options/ClientOptions.php | 223 +++++++++++------- Gax/src/Options/OptionsTrait.php | 16 +- Gax/src/Options/TransportOptions.php | 78 ++++-- .../GrpcFallbackTransportOptions.php | 14 +- .../TransportOptions/GrpcTransportOptions.php | 22 +- .../TransportOptions/RestTransportOptions.php | 18 +- Gax/tests/Unit/GapicClientTraitTest.php | 77 +++++- Gax/tests/Unit/Options/ClientOptionsTest.php | 134 +++++++++++ 12 files changed, 526 insertions(+), 191 deletions(-) create mode 100644 Gax/tests/Unit/Options/ClientOptionsTest.php diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index e5b583b6920c..12a8e870bbd5 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -35,6 +35,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()`, extend `Google\ApiCore\Options\ClientOptions` (or use `ClientOptions::setCustomOption()` / `getCustomOption()`), pass the `ClientOptions` instance to `buildClientOptions()` / `setClientOptions()` (or override `protected function createClientOptions(array $options): ClientOptions`), and read `$this->getClientOptions()` on the client. - **`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..d8cc7a63ed8c 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); + if ($this->clientOptions instanceof ClientOptions) { + $options = $this->clientOptions->fromArray($optionsArray); + } else { + $options = $this->clientOptions = $this->createClientOptions($optionsArray); + } + $hasEmulator = (bool) ($options['hasEmulator'] ?? false); $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( $this->serviceName, @@ -439,7 +445,7 @@ private function createTransport( * * @return OperationsClient */ - private function createOperationsClient(array $options) + protected function createOperationsClient(array $options) { // Unset client-specific configuration options unset( @@ -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 ae76b58effca..51fda74400f4 100644 --- a/Gax/src/Options/CallOptions.php +++ b/Gax/src/Options/CallOptions.php @@ -77,7 +77,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); } @@ -102,8 +102,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; @@ -112,8 +114,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; @@ -138,8 +142,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; @@ -149,9 +155,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; @@ -161,23 +167,29 @@ 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; return $this; } - public function setAudience(?string $audience): self + /** + * @return static + */ + public function setAudience(?string $audience): static { $this->audience = $audience; diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 66ea4affe48a..37387636a388 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,41 @@ 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; + + protected array $customOptions = []; /** * @param array $options { @@ -170,55 +169,74 @@ class ClientOptions implements ArrayAccess, OptionsInterface * A PSR-3 compliant logger. * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } /** - * 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); + if (!isset($this->transportConfig) || isset($arr['transportConfig'])) { + $this->setTransportConfig($arr['transportConfig'] ?? []); + } + + // serviceAddress is deprecated and acts as an alias for apiEndpoint + if (isset($arr['serviceAddress'])) { + $arr['apiEndpoint'] = $arr['serviceAddress']; + unset($arr['serviceAddress']); + } + + foreach ($arr as $key => $value) { + if ($key === 'transportConfig') { + continue; + } + $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $key, '-_')); + if (method_exists($this, $setter)) { + $this->$setter($value); + } else { + $this->setCustomOption((string) $key, $value); + } + } + + 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 +246,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 +262,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 +275,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 +287,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 +297,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 +314,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 +326,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 +341,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 +353,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 +365,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 +377,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 +389,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 +402,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 +414,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,12 +428,50 @@ 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; return $this; } + + /** + * Set a custom or experimental option not explicitly defined on ClientOptions. + * + * @param string $key + * @param mixed $value + * + * @return static + */ + public function setCustomOption(string $key, mixed $value): static + { + $this->customOptions[$key] = $value; + + return $this; + } + + /** + * Get a custom or experimental option value. + * + * @param string $key + * @param mixed $default + * + * @return mixed + */ + public function getCustomOption(string $key, mixed $default = null): mixed + { + return $this->customOptions[$key] ?? $default; + } + + /** + * Get all custom or experimental options. + * + * @return array + */ + public function getCustomOptions(): array + { + return $this->customOptions; + } } diff --git a/Gax/src/Options/OptionsTrait.php b/Gax/src/Options/OptionsTrait.php index 444027c66190..b52472341eb4 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"); @@ -56,7 +56,7 @@ private static function validateFileExists(string $filePath) public function offsetExists($offset): bool { - return isset($this->$offset); + return isset($this->$offset) || isset($this->customOptions[$offset]); } /** @@ -65,7 +65,11 @@ public function offsetExists($offset): bool #[\ReturnTypeWillChange] public function offsetGet($offset) { - return $this->$offset; + if (property_exists($this, $offset)) { + return $this->$offset; + } + + return $this->customOptions[$offset] ?? null; } /** @@ -88,10 +92,16 @@ public function toArray(): array { $arr = []; foreach (get_object_vars($this) as $key => $value) { + if ($key === 'customOptions') { + continue; + } $arr[$key] = $value instanceof OptionsInterface ? $value->toArray() : $value; } + if (isset($this->customOptions) && is_array($this->customOptions)) { + $arr += $this->customOptions; + } return $arr; } } diff --git a/Gax/src/Options/TransportOptions.php b/Gax/src/Options/TransportOptions.php index af8fa3994d44..2b9cc6a83ad7 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,98 @@ class TransportOptions implements ArrayAccess, OptionsInterface * @type array $rest * } */ - public function __construct(array $options) + public function __construct(array $options = []) { $this->fromArray($options); } /** - * 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) || isset($this->customOptions[$offset]); + } + + /** + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + if ($offset === 'grpc-fallback') { + $offset = 'grpcFallback'; + } + if (property_exists($this, $offset)) { + return $this->$offset; + } + + return $this->customOptions[$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 17ef0f4c2986..645553d3380e 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1093,16 +1093,54 @@ 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') + ->setCustomOption('addNewOption', true); + + $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->getCustomOption('addNewOption')); + $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', + 'customFlag' => true, + ]); $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()); + $this->assertTrue($resolvedOptions->getCustomOption('customFlag')); } private function buildClientToTestModifyCallMethods($clientClass = null) @@ -1957,6 +1995,7 @@ class StubGapicClient createOperationsClient as public; createTransport as public; determineMtlsEndpoint as public; + getClientOptions as public; getGapicVersion as public; getCredentialsWrapper as public; getPagedListResponse as public; @@ -2027,13 +2066,27 @@ public function get($name) } } +class StubCustomClientOptions 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; + } +} + 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) @@ -2138,6 +2191,7 @@ public function getOperation($request) class GapicV2SurfaceClient { use GapicClientTrait { + getClientOptions as public; startCall as public; } use GapicClientStubTrait; @@ -2145,7 +2199,7 @@ class GapicV2SurfaceClient ClientDefaultsTrait::getClientDefaults insteadof GapicClientTrait; } - public function __construct(array $options = []) + public function __construct(array|\Google\ApiCore\Options\ClientOptions $options = []) { $clientOptions = $this->buildClientOptions($options); $this->setClientOptions($clientOptions); @@ -2155,5 +2209,4 @@ public function getAgentHeader() { return $this->agentHeader; } - } diff --git a/Gax/tests/Unit/Options/ClientOptionsTest.php b/Gax/tests/Unit/Options/ClientOptionsTest.php new file mode 100644 index 000000000000..e88d925e4499 --- /dev/null +++ b/Gax/tests/Unit/Options/ClientOptionsTest.php @@ -0,0 +1,134 @@ +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 testCustomOptions() + { + $options = (new ClientOptions([ + 'experimentalOption' => 'exp-val', + ]))->setCustomOption('anotherOption', 123); + + $this->assertTrue(isset($options['experimentalOption'])); + $this->assertTrue(isset($options['anotherOption'])); + $this->assertFalse(isset($options['nonExistentOption'])); + $this->assertEquals('exp-val', $options['experimentalOption']); + $this->assertEquals('exp-val', $options->getCustomOption('experimentalOption')); + $this->assertEquals(123, $options['anotherOption']); + $this->assertEquals('default', $options->getCustomOption('nonExistentOption', 'default')); + + $arr = $options->toArray(); + $this->assertArrayNotHasKey('customOptions', $arr); + $this->assertEquals('exp-val', $arr['experimentalOption']); + $this->assertEquals(123, $arr['anotherOption']); + } + + 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 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']); + } +} From cd31e2f36cbf9fd1afb7cb9146c5ea6f4b8e280e Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 17:52:05 +0000 Subject: [PATCH 2/6] feat(Gax): support array-access mutation on ClientOptions --- Gax/src/Options/ClientOptions.php | 2 +- Gax/src/Options/OptionsTrait.php | 22 ++++++++++++++++++-- Gax/src/Options/TransportOptions.php | 5 +++-- Gax/tests/Unit/Options/ClientOptionsTest.php | 13 ++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 37387636a388..112d145bfd24 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -198,7 +198,7 @@ public function fromArray(array $arr): static continue; } $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $key, '-_')); - if (method_exists($this, $setter)) { + if ($setter !== 'setCustomOption' && method_exists($this, $setter)) { $this->$setter($value); } else { $this->setCustomOption((string) $key, $value); diff --git a/Gax/src/Options/OptionsTrait.php b/Gax/src/Options/OptionsTrait.php index b52472341eb4..23c9eab0e881 100644 --- a/Gax/src/Options/OptionsTrait.php +++ b/Gax/src/Options/OptionsTrait.php @@ -63,13 +63,22 @@ public function offsetExists($offset): bool * @return mixed */ #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function &offsetGet($offset) { if (property_exists($this, $offset)) { return $this->$offset; } - return $this->customOptions[$offset] ?? null; + if (isset($this->customOptions) && is_array($this->customOptions)) { + if (!array_key_exists($offset, $this->customOptions)) { + $null = null; + return $null; + } + return $this->customOptions[$offset]; + } + + $null = null; + return $null; } /** @@ -77,6 +86,15 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value): void { + $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $offset, '-_')); + if ($setter !== 'setCustomOption' && method_exists($this, $setter)) { + $this->$setter($value); + return; + } + if (method_exists($this, 'setCustomOption')) { + $this->setCustomOption((string) $offset, $value); + return; + } throw new BadMethodCallException('Cannot set options through array access. Use the setters instead'); } diff --git a/Gax/src/Options/TransportOptions.php b/Gax/src/Options/TransportOptions.php index 2b9cc6a83ad7..5f1dd6732068 100644 --- a/Gax/src/Options/TransportOptions.php +++ b/Gax/src/Options/TransportOptions.php @@ -132,7 +132,7 @@ public function offsetExists($offset): bool * @return mixed */ #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function &offsetGet($offset) { if ($offset === 'grpc-fallback') { $offset = 'grpcFallback'; @@ -141,7 +141,8 @@ public function offsetGet($offset) return $this->$offset; } - return $this->customOptions[$offset] ?? null; + $null = null; + return $null; } public function toArray(): array diff --git a/Gax/tests/Unit/Options/ClientOptionsTest.php b/Gax/tests/Unit/Options/ClientOptionsTest.php index e88d925e4499..eed52f109db6 100644 --- a/Gax/tests/Unit/Options/ClientOptionsTest.php +++ b/Gax/tests/Unit/Options/ClientOptionsTest.php @@ -131,4 +131,17 @@ public function setLoginCustomerId(?string $loginCustomerId): static $this->assertEquals('dev-123', $arr['developerToken']); $this->assertEquals('cust-456', $arr['loginCustomerId']); } + + public function testArrayAccessSetAndEmulatorConfig() + { + $options = new ClientOptions(); + $options['apiEndpoint'] ??= 'localhost:8086'; + $options['transportConfig']['grpc']['stubOpts']['credentials'] ??= 'insecure-channel-creds'; + $options['customOption'] = 'custom-value'; + + $this->assertEquals('localhost:8086', $options['apiEndpoint']); + $this->assertEquals('insecure-channel-creds', $options['transportConfig']['grpc']['stubOpts']['credentials']); + $this->assertEquals('custom-value', $options['customOption']); + $this->assertEquals('custom-value', $options->getCustomOption('customOption')); + } } From 0068cdbf1b57aabc11d7043f592613c24497185b Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Wed, 30 Sep 2026 18:13:39 +0000 Subject: [PATCH 3/6] refactor(Gax): remove customOptions and return-by-reference offsetGet --- Gax/MIGRATING.md | 2 +- Gax/src/GapicClientTrait.php | 2 +- Gax/src/Options/ClientOptions.php | 44 +------------------- Gax/src/Options/OptionsTrait.php | 31 ++------------ Gax/src/Options/TransportOptions.php | 11 ++--- Gax/tests/Unit/GapicClientTraitTest.php | 6 +-- Gax/tests/Unit/Options/ClientOptionsTest.php | 27 +----------- 7 files changed, 12 insertions(+), 111 deletions(-) diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 12a8e870bbd5..7e8f2a66d409 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -35,7 +35,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()`, extend `Google\ApiCore\Options\ClientOptions` (or use `ClientOptions::setCustomOption()` / `getCustomOption()`), pass the `ClientOptions` instance to `buildClientOptions()` / `setClientOptions()` (or override `protected function createClientOptions(array $options): ClientOptions`), and read `$this->getClientOptions()` on the client. +- **`ClientOptionsTrait::modifyClientOptions()`**: Removed. Instead of mutating the options array in `modifyClientOptions()`, extend `Google\ApiCore\Options\ClientOptions`, pass the `ClientOptions` instance to `buildClientOptions()` / `setClientOptions()` (or override `protected function createClientOptions(array $options): ClientOptions`), and read `$this->getClientOptions()` on the client. - **`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/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index d8cc7a63ed8c..6a04b3cfa4dc 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -302,12 +302,12 @@ private function setClientOptions(array|ClientOptions $options): void 'libVersion', ]); + $hasEmulator = (bool) ($optionsArray['hasEmulator'] ?? false); if ($this->clientOptions instanceof ClientOptions) { $options = $this->clientOptions->fromArray($optionsArray); } else { $options = $this->clientOptions = $this->createClientOptions($optionsArray); } - $hasEmulator = (bool) ($options['hasEmulator'] ?? false); $this->serviceName = $options['serviceName']; $this->retrySettings = RetrySettings::load( $this->serviceName, diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index 112d145bfd24..d6b183fbff44 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -95,8 +95,6 @@ class ClientOptions implements ArrayAccess, OptionsInterface protected null|false|LoggerInterface $logger = null; - protected array $customOptions = []; - /** * @param array $options { * @type string $apiEndpoint @@ -198,10 +196,8 @@ public function fromArray(array $arr): static continue; } $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $key, '-_')); - if ($setter !== 'setCustomOption' && method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($value); - } else { - $this->setCustomOption((string) $key, $value); } } @@ -436,42 +432,4 @@ public function setLogger(null|false|LoggerInterface $logger): static return $this; } - - /** - * Set a custom or experimental option not explicitly defined on ClientOptions. - * - * @param string $key - * @param mixed $value - * - * @return static - */ - public function setCustomOption(string $key, mixed $value): static - { - $this->customOptions[$key] = $value; - - return $this; - } - - /** - * Get a custom or experimental option value. - * - * @param string $key - * @param mixed $default - * - * @return mixed - */ - public function getCustomOption(string $key, mixed $default = null): mixed - { - return $this->customOptions[$key] ?? $default; - } - - /** - * Get all custom or experimental options. - * - * @return array - */ - public function getCustomOptions(): array - { - return $this->customOptions; - } } diff --git a/Gax/src/Options/OptionsTrait.php b/Gax/src/Options/OptionsTrait.php index 23c9eab0e881..86e67f58b794 100644 --- a/Gax/src/Options/OptionsTrait.php +++ b/Gax/src/Options/OptionsTrait.php @@ -56,29 +56,16 @@ protected static function validateFileExists(string $filePath) public function offsetExists($offset): bool { - return isset($this->$offset) || isset($this->customOptions[$offset]); + return isset($this->$offset); } /** * @return mixed */ #[\ReturnTypeWillChange] - public function &offsetGet($offset) + public function offsetGet($offset) { - if (property_exists($this, $offset)) { - return $this->$offset; - } - - if (isset($this->customOptions) && is_array($this->customOptions)) { - if (!array_key_exists($offset, $this->customOptions)) { - $null = null; - return $null; - } - return $this->customOptions[$offset]; - } - - $null = null; - return $null; + return $this->$offset ?? null; } /** @@ -87,14 +74,10 @@ public function &offsetGet($offset) public function offsetSet($offset, $value): void { $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $offset, '-_')); - if ($setter !== 'setCustomOption' && method_exists($this, $setter)) { + if (method_exists($this, $setter)) { $this->$setter($value); return; } - if (method_exists($this, 'setCustomOption')) { - $this->setCustomOption((string) $offset, $value); - return; - } throw new BadMethodCallException('Cannot set options through array access. Use the setters instead'); } @@ -110,16 +93,10 @@ public function toArray(): array { $arr = []; foreach (get_object_vars($this) as $key => $value) { - if ($key === 'customOptions') { - continue; - } $arr[$key] = $value instanceof OptionsInterface ? $value->toArray() : $value; } - if (isset($this->customOptions) && is_array($this->customOptions)) { - $arr += $this->customOptions; - } return $arr; } } diff --git a/Gax/src/Options/TransportOptions.php b/Gax/src/Options/TransportOptions.php index 5f1dd6732068..37566c7b7228 100644 --- a/Gax/src/Options/TransportOptions.php +++ b/Gax/src/Options/TransportOptions.php @@ -125,24 +125,19 @@ public function offsetExists($offset): bool if ($offset === 'grpc-fallback') { $offset = 'grpcFallback'; } - return isset($this->$offset) || isset($this->customOptions[$offset]); + return isset($this->$offset); } /** * @return mixed */ #[\ReturnTypeWillChange] - public function &offsetGet($offset) + public function offsetGet($offset) { if ($offset === 'grpc-fallback') { $offset = 'grpcFallback'; } - if (property_exists($this, $offset)) { - return $this->$offset; - } - - $null = null; - return $null; + return $this->$offset ?? null; } public function toArray(): array diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 645553d3380e..ede75c76f6f6 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -1113,8 +1113,7 @@ public function getDeveloperToken(): ?string $options = (new ($customOptionsClass::class)()) ->setDisableRetries(true) ->setApiEndpoint('abc123') - ->setDeveloperToken('dev-token-123') - ->setCustomOption('addNewOption', true); + ->setDeveloperToken('dev-token-123'); $client = new GapicV2SurfaceClient($options); $resolvedOptions = $client->getClientOptions(); @@ -1122,7 +1121,6 @@ public function getDeveloperToken(): ?string $this->assertInstanceOf($customOptionsClass::class, $resolvedOptions); $this->assertNotSame($options, $resolvedOptions); $this->assertSame('dev-token-123', $resolvedOptions->getDeveloperToken()); - $this->assertTrue($resolvedOptions->getCustomOption('addNewOption')); $this->assertTrue($resolvedOptions['disableRetries']); $this->assertEquals('abc123', $resolvedOptions['apiEndpoint']); $this->assertEquals('test.interface.v1.api', $resolvedOptions['serviceName']); @@ -1133,14 +1131,12 @@ public function testCreateClientOptionsOverride() $client = new StubGapicClientExtension(); $updatedOptions = $client->buildClientOptions([ 'developer-token' => 'dev-token-456', - 'customFlag' => true, ]); $client->setClientOptions($updatedOptions); $resolvedOptions = $client->getClientOptions(); $this->assertInstanceOf(StubCustomClientOptions::class, $resolvedOptions); $this->assertSame('dev-token-456', $resolvedOptions->getDeveloperToken()); - $this->assertTrue($resolvedOptions->getCustomOption('customFlag')); } private function buildClientToTestModifyCallMethods($clientClass = null) diff --git a/Gax/tests/Unit/Options/ClientOptionsTest.php b/Gax/tests/Unit/Options/ClientOptionsTest.php index eed52f109db6..2688a972f779 100644 --- a/Gax/tests/Unit/Options/ClientOptionsTest.php +++ b/Gax/tests/Unit/Options/ClientOptionsTest.php @@ -70,26 +70,6 @@ public function testServiceAddressAlias() $this->assertEquals('fluid.endpoint:443', $fluid['apiEndpoint']); } - public function testCustomOptions() - { - $options = (new ClientOptions([ - 'experimentalOption' => 'exp-val', - ]))->setCustomOption('anotherOption', 123); - - $this->assertTrue(isset($options['experimentalOption'])); - $this->assertTrue(isset($options['anotherOption'])); - $this->assertFalse(isset($options['nonExistentOption'])); - $this->assertEquals('exp-val', $options['experimentalOption']); - $this->assertEquals('exp-val', $options->getCustomOption('experimentalOption')); - $this->assertEquals(123, $options['anotherOption']); - $this->assertEquals('default', $options->getCustomOption('nonExistentOption', 'default')); - - $arr = $options->toArray(); - $this->assertArrayNotHasKey('customOptions', $arr); - $this->assertEquals('exp-val', $arr['experimentalOption']); - $this->assertEquals(123, $arr['anotherOption']); - } - public function testSubclassClientOptions() { $options = new class([ @@ -132,16 +112,11 @@ public function setLoginCustomerId(?string $loginCustomerId): static $this->assertEquals('cust-456', $arr['loginCustomerId']); } - public function testArrayAccessSetAndEmulatorConfig() + public function testArrayAccessSet() { $options = new ClientOptions(); $options['apiEndpoint'] ??= 'localhost:8086'; - $options['transportConfig']['grpc']['stubOpts']['credentials'] ??= 'insecure-channel-creds'; - $options['customOption'] = 'custom-value'; $this->assertEquals('localhost:8086', $options['apiEndpoint']); - $this->assertEquals('insecure-channel-creds', $options['transportConfig']['grpc']['stubOpts']['credentials']); - $this->assertEquals('custom-value', $options['customOption']); - $this->assertEquals('custom-value', $options->getCustomOption('customOption')); } } From ed0d07999190984a8ef6ee8e4dcd26b54d656926 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 1 Oct 2026 21:12:24 +0000 Subject: [PATCH 4/6] fix(Gax): keep createOperationsClient private and fix GapicV2SurfaceClient test --- Gax/src/GapicClientTrait.php | 2 +- Gax/tests/Unit/GapicClientTraitTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index 6a04b3cfa4dc..46a0e2e3578c 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -445,7 +445,7 @@ private function createTransport( * * @return OperationsClient */ - protected function createOperationsClient(array $options) + private function createOperationsClient(array $options) { // Unset client-specific configuration options unset( diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 1c8570f2913e..61a30a8a0e6e 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -2311,7 +2311,7 @@ public function __construct(array|\Google\ApiCore\Options\ClientOptions $options { $clientOptions = $this->buildClientOptions($options); $this->setClientOptions($clientOptions); - $this->operationsClient = $this->createOperationsClient($clientOptions->toArray()); + $this->operationsClient = $this->createOperationsClient($clientOptions); } public function getAgentHeader() From 7dbe8e54d3a50fad82ec423f37367b3cf010824e Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Thu, 12 Nov 2026 18:37:25 +0000 Subject: [PATCH 5/6] refactor(Gax): use explicit setter calls in ClientOptions::fromArray and keep ArrayAccess read-only --- Gax/src/Options/ClientOptions.php | 43 +++++++++++--------- Gax/src/Options/OptionsTrait.php | 5 --- Gax/src/Options/TransportOptions.php | 7 ++++ Gax/tests/Unit/GapicClientTraitTest.php | 8 ++++ Gax/tests/Unit/Options/ClientOptionsTest.php | 31 ++++++++++++-- 5 files changed, 67 insertions(+), 27 deletions(-) diff --git a/Gax/src/Options/ClientOptions.php b/Gax/src/Options/ClientOptions.php index d6b183fbff44..8a436e43fb1f 100644 --- a/Gax/src/Options/ClientOptions.php +++ b/Gax/src/Options/ClientOptions.php @@ -172,6 +172,13 @@ 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 properties. * @@ -181,25 +188,23 @@ public function __construct(array $options = []) */ public function fromArray(array $arr): static { - if (!isset($this->transportConfig) || isset($arr['transportConfig'])) { - $this->setTransportConfig($arr['transportConfig'] ?? []); - } - - // serviceAddress is deprecated and acts as an alias for apiEndpoint - if (isset($arr['serviceAddress'])) { - $arr['apiEndpoint'] = $arr['serviceAddress']; - unset($arr['serviceAddress']); - } - - foreach ($arr as $key => $value) { - if ($key === 'transportConfig') { - continue; - } - $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $key, '-_')); - if (method_exists($this, $setter)) { - $this->$setter($value); - } - } + $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; } diff --git a/Gax/src/Options/OptionsTrait.php b/Gax/src/Options/OptionsTrait.php index 86e67f58b794..865a5f10d2d2 100644 --- a/Gax/src/Options/OptionsTrait.php +++ b/Gax/src/Options/OptionsTrait.php @@ -73,11 +73,6 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value): void { - $setter = 'set' . str_replace(['-', '_'], '', ucwords((string) $offset, '-_')); - if (method_exists($this, $setter)) { - $this->$setter($value); - return; - } throw new BadMethodCallException('Cannot set options through array access. Use the setters instead'); } diff --git a/Gax/src/Options/TransportOptions.php b/Gax/src/Options/TransportOptions.php index 37566c7b7228..57db42eb345e 100644 --- a/Gax/src/Options/TransportOptions.php +++ b/Gax/src/Options/TransportOptions.php @@ -63,6 +63,13 @@ 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 properties. * diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 86572cfe982f..e3cc803b6e24 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -2185,6 +2185,14 @@ 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; diff --git a/Gax/tests/Unit/Options/ClientOptionsTest.php b/Gax/tests/Unit/Options/ClientOptionsTest.php index 2688a972f779..9b4b6ad0a756 100644 --- a/Gax/tests/Unit/Options/ClientOptionsTest.php +++ b/Gax/tests/Unit/Options/ClientOptionsTest.php @@ -32,6 +32,7 @@ namespace Google\ApiCore\Tests\Unit\Options; +use BadMethodCallException; use Google\ApiCore\Options\ClientOptions; use PHPUnit\Framework\TestCase; @@ -79,6 +80,15 @@ public function testSubclassClientOptions() 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; @@ -112,11 +122,26 @@ public function setLoginCustomerId(?string $loginCustomerId): static $this->assertEquals('cust-456', $arr['loginCustomerId']); } - public function testArrayAccessSet() + public function testArrayAccessSetThrowsException() { + $this->expectException(BadMethodCallException::class); + $options = new ClientOptions(); - $options['apiEndpoint'] ??= 'localhost:8086'; + $options['apiEndpoint'] = 'localhost:8086'; + } - $this->assertEquals('localhost:8086', $options['apiEndpoint']); + 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']); } } From 090d63c208f994f406b22e4c96516ba630d982c0 Mon Sep 17 00:00:00 2001 From: Brent Shaffer Date: Fri, 13 Nov 2026 19:33:37 +0000 Subject: [PATCH 6/6] docs(Gax): update MIGRATING.md for ClientOptions::fromArray --- Gax/MIGRATING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gax/MIGRATING.md b/Gax/MIGRATING.md index 47c5c734a955..13bd49d06607 100644 --- a/Gax/MIGRATING.md +++ b/Gax/MIGRATING.md @@ -36,7 +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()`, extend `Google\ApiCore\Options\ClientOptions`, pass the `ClientOptions` instance to `buildClientOptions()` / `setClientOptions()` (or override `protected function createClientOptions(array $options): ClientOptions`), and read `$this->getClientOptions()` on the client. +- **`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()`.