Skip to content
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"google/gax": "^1.48.0",
"google/cloud": "dev-longrunning-v1",
"opis/closure": "^4.5"
},
"scripts": {
Expand Down
29 changes: 27 additions & 2 deletions src/Ast/PhpClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,16 @@ public function __construct(
public bool $abstract
) {
$this->traits = Set::new();
$this->interfaces = Set::new();
$this->members = Vector::new();
}

/** @var Set *Readonly* Set of ResolvedType; the traits used by this class. */
public Set $traits;

/** @var Set *Readonly* Set of ResolvedType; the interfaces implemented by this class. */
public Set $interfaces;

/** @var Vector *Readonly* Vector of PhpClassMember; all members of this class. */
public Vector $members;

Expand All @@ -71,6 +75,25 @@ public function withTrait(?ResolvedType $trait): PhpClass
return $this->clone(fn ($clone) => $clone->traits = $clone->traits->add($trait));
}

/**
* Create a class with an additional interface.
*
* @param ?ResolvedType $interface Interface to add. Must be a type which is an interface.
*
* @return PhpClass
*/
public function withInterface(?ResolvedType $interface): PhpClass
{
// No-op, just return the same class.
if (is_null($interface)) {
return $this;
}
if (!$interface->type->isClass()) {
throw new Exception('Only classes (interfaces) may be used as an interface.');
}
return $this->clone(fn ($clone) => $clone->interfaces = $clone->interfaces->add($interface));
}

/**
* Create a class with an additional member.
*
Expand Down Expand Up @@ -120,8 +143,10 @@ public function toCode(): string

return
$this->phpDocToCode() .
"{$class} {$this->type->name}{$extends}\n" .
"{\n" .
"{$class} {$this->type->name}{$extends}" .
(count($this->interfaces) >= 1 ? ' implements ' : '') .
$this->interfaces->toVector()->map(fn ($x) => "{$x->toCode()}")->join(', ') .
"\n{\n" .
$this->traits->toVector()->map(fn ($x) => "use {$x->toCode()};\n")->join() .
(count($this->traits) >= 1 ? "\n" : '') .
$this->members->map(fn ($x) => $x->toCode() . "\n")->join() .
Expand Down
3 changes: 1 addition & 2 deletions src/Ast/PhpFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ public function toCode(): string
$lines = [
'<?php',
$this->headerLines->map(fn ($x) => "{$x}\n")->join(),
// TODO(miraleung): Uncomment this when the client libraries support only PHP 7+.
// "declare(strict_types=1);\n",
"declare(strict_types=1);\n",
];

if ($this->class) {
Expand Down
48 changes: 39 additions & 9 deletions src/Generation/EmulatorSupportGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

namespace Google\Generator\Generation;

use Google\ApiCore\Options\ClientOptions;
use Google\Generator\Ast\Access;
use Google\Generator\Ast\AST;
use Google\Generator\Ast\PhpDoc;
Expand Down Expand Up @@ -54,18 +55,27 @@ public static function generateEmulatorSupport(ServiceDetails $serviceDetails, S
$schemeVar = AST::var('scheme');
$searchVar = AST::var('search');
$optionsVar = AST::var('options');
$transportConfigIndexVar = AST::index(AST::index(AST::index(AST::index(
$optionsVar,
'transportConfig'
), 'grpc'), 'stubOpts'), 'credentials');
$stubOptsVar = AST::var('stubOpts');
$clientOptionsType = $ctx->type(Type::fromName(ClientOptions::class));
$channelCredentialsType = $ctx->type(Type::fromName("Grpc\ChannelCredentials"));
$insecureCredentialsType = $ctx->type(Type::fromName("Google\ApiCore\InsecureCredentialsWrapper"));
$optionsType = ResolvedType::union(
Type::array(),
Type::fromName(ClientOptions::class)
);
$grpcTransportOptionsExpr = AST::index(AST::index($optionsVar, 'transportConfig'), 'grpc');
$transportConfigIndexVar = AST::index(AST::index(
$grpcTransportOptionsExpr,
'stubOpts'
), 'credentials');

if (!array_key_exists($fullClassName, self::$emulatorSupportClients)) {
return null;
}

return AST::method(self::DEFAULT_EMULATOR_CONFIG_FN)
->withAccess(Access::PRIVATE)
->withParams(AST::param(ResolvedType::array(), $optionsVar))
->withParams(AST::param($optionsType, $optionsVar))
->withBody(AST::block(
AST::assign($emulatorHostVar, AST::call(AST::GET_ENV)(self::$emulatorSupportClients[$fullClassName])),
AST::if(AST::call(AST::EMPTY)($emulatorHostVar))->then(AST::return($optionsVar)),
Expand All @@ -74,26 +84,46 @@ public static function generateEmulatorSupport(ServiceDetails $serviceDetails, S
AST::assign($searchVar, AST::binaryOp($schemeVar, '.', '://')),
AST::assign($emulatorHostVar, AST::call(AST::STRING_REPLACE)($searchVar, '', $emulatorHostVar)),
)),
AST::if(AST::binaryOp($optionsVar, 'instanceof', $clientOptionsType))
->then(AST::block(
AST::assign($optionsVar, AST::literal('clone ' . $optionsVar->toCode())),
AST::if(AST::not(AST::call(AST::ISSET)(AST::index($optionsVar, 'apiEndpoint'))))
->then(AST::call($optionsVar, AST::method('setApiEndpoint'))($emulatorHostVar)),
AST::if(AST::call(AST::CLASS_EXISTS)(AST::access($channelCredentialsType, AST::CLS)))
->then(AST::block(
AST::assign($stubOptsVar, AST::index($grpcTransportOptionsExpr, 'stubOpts')),
AST::nullCoalescingAssign(
AST::index($stubOptsVar, 'credentials'),
AST::staticCall($channelCredentialsType, AST::method('createInsecure'))()
),
AST::call($grpcTransportOptionsExpr, AST::method('setStubOpts'))($stubOptsVar),
)),
AST::if(AST::not(AST::call(AST::ISSET)(AST::index($optionsVar, 'credentials'))))
->then(AST::call($optionsVar, AST::method('setCredentials'))(
AST::new($insecureCredentialsType)()
)),
AST::return($optionsVar),
)),
AST::nullCoalescingAssign(AST::index($optionsVar, 'apiEndpoint'), $emulatorHostVar),
AST::if(AST::call(AST::CLASS_EXISTS)(
AST::access($ctx->type(Type::fromName("Grpc\ChannelCredentials")), AST::CLS)
AST::access($channelCredentialsType, AST::CLS)
))
->then(AST::block(
AST::nullCoalescingAssign($transportConfigIndexVar, AST::staticCall(
$ctx->type((Type::fromName("Grpc\ChannelCredentials"))),
$channelCredentialsType,
AST::method('createInsecure')
)()),
)),
AST::nullCoalescingAssign(
AST::index($optionsVar, 'credentials'),
AST::new($ctx->type((Type::fromName("Google\ApiCore\InsecureCredentialsWrapper"))))()
AST::new($insecureCredentialsType)()
),
AST::return($optionsVar)
), AST::return(AST::array([])))
->withPhpDoc(PhpDoc::block(
PhpDoc::text('Configure the gapic configuration to use a service emulator.')
))
->withReturnType($ctx->type(Type::array()));
->withReturnType($optionsType);
}

public static function generateEmulatorOptions(ServiceDetails $serviceDetails, AST $options)
Expand Down
117 changes: 69 additions & 48 deletions src/Generation/GapicClientGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,17 @@
use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\GapicClientTrait;
use Google\ApiCore\HeaderCredentialsInterface;
use Google\ApiCore\IamProviderInterface;
use Google\ApiCore\LongRunningOperationProviderInterface;
use Google\ApiCore\OperationResponse;
use Google\ApiCore\OperationsClientInterface;
use Google\ApiCore\Options\ClientOptions;
use Google\ApiCore\PathTemplate;
use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\ResourceHelperTrait;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\ServiceInterface;
use Google\ApiCore\Transport\GrpcTransport;
use Google\ApiCore\Transport\RestTransport;
use Google\ApiCore\Transport\TransportInterface;
Expand Down Expand Up @@ -106,9 +111,7 @@ private function generateImpl(): PhpFile

private function generateClass(): PhpClass
{
return AST::class(
$this->serviceDetails->gapicClientType,
final: true)
return AST::class($this->serviceDetails->gapicClientType, final: true)
->withPhpDoc(PhpDoc::block(
PhpDoc::preFormattedText(
$this->serviceDetails->docLines->skip(1)
Expand Down Expand Up @@ -139,6 +142,22 @@ private function generateClass(): PhpClass
!$this->serviceDetails->isDeprecated ? null : PhpDoc::deprecated(ServiceDetails::DEPRECATED_MSG),
$this->serviceDetails->streamingOnly ? null : $this->magicAsyncDocs(),
))
->withInterface($this->ctx->type(Type::fromName(ServiceInterface::class)))
->withInterface(
$this->serviceDetails->hasLro
? $this->ctx->type(Type::fromName(LongRunningOperationProviderInterface::class))
: null
)
->withInterface(
$this->serviceDetails->hasIamMethods()
? $this->ctx->type(Type::fromName(IamProviderInterface::class))
: null
)
->withInterface(
$this->serviceDetails->hasOperationsMethods()
? $this->ctx->type(Type::fromName(OperationsClientInterface::class))
: null
)
->withTrait($this->ctx->type(Type::fromName(GapicClientTrait::class)))
->withTrait(
$this->serviceDetails->hasResources ? $this->ctx->type(Type::fromName(ResourceHelperTrait::class)): null
Expand Down Expand Up @@ -264,9 +283,9 @@ private function magicMethod(): ?PhpClassMember

// params
$methodVar = AST::var('method');
$methodParam = AST::param(null, $methodVar);
$methodParam = AST::param(ResolvedType::string(), $methodVar);
$argsVar = AST::var('args');
$argsParam = AST::param(null, $argsVar);
$argsParam = AST::param(ResolvedType::array(), $argsVar);
$triggerError = AST::call(AST::TRIGGER_ERROR)(AST::concat('Call to undefined method ', AST::__CLASS__, AST::interpolatedString('::$method()')), AST::E_USER_ERROR);

return AST::method('__call')
Expand Down Expand Up @@ -309,6 +328,7 @@ private function operationMethods(): Vector
// getOperationsClient returns the operation client instance.
$getOperationsClient = AST::method('getOperationsClient')
->withAccess(Access::PUBLIC)
->withReturnType($this->ctx->type($ctype))
->withBody(AST::block(
AST::return(AST::access(AST::THIS, $this->operationsClient()))
))
Expand All @@ -330,6 +350,7 @@ private function operationMethods(): Vector
: AST::array([]);
$getDefaultOperationDescriptor = AST::method('getDefaultOperationDescriptor')
->withAccess(Access::PRIVATE)
->withReturnType(ResolvedType::array())
->withBody(AST::block(
AST::return($defaultOperationDescriptor)
))
Expand All @@ -347,7 +368,11 @@ private function operationMethods(): Vector
$operation = AST::var('operation');
$resumeOperation = AST::method('resumeOperation')
->withAccess(Access::PUBLIC)
->withParams(AST::param(null, $operationName), AST::param(null, $methodName, AST::NULL))
->withParams(
AST::param(ResolvedType::string(), $operationName),
AST::param(ResolvedType::string(true), $methodName, AST::NULL)
)
->withReturnType($this->ctx->type(Type::fromName(OperationResponse::class)))
->withBody(AST::block(
AST::assign($options, AST::ternary(
AST::binaryOp(
Expand Down Expand Up @@ -387,39 +412,38 @@ private function operationMethods(): Vector
));
$methods = $methods->append($resumeOperation);

// write createOperationsClient method for new surface clients
// @TODO: Remove this once GAX V2 is released
$operationsClientType = $this->serviceDetails->hasCustomOp
? $this->ctx->type($this->serviceDetails->customOperationServiceClientType)
: $this->ctx->type(Type::fromName(OperationsClient::class));
$createOperationsClient = AST::method('createOperationsClient')
->withAccess(Access::PRIVATE)
->withParams(AST::param(ResolvedType::array(), $options))
->withBody(AST::block(
'// Unset client-specific configuration options',
AST::call(AST::method('unset'))(
AST::index($options, 'serviceName'),
AST::index($options, 'clientConfig'),
AST::index($options, 'descriptorsConfigPath'),
),
PHP_EOL,
AST::if(
AST::call(AST::method('isset'))(AST::index($options, 'operationsClient'))
)->then(AST::return(AST::index($options, 'operationsClient'))),
PHP_EOL,
AST::return(AST::new($operationsClientType)($options))
))
->withPhpDoc(PhpDoc::block(
PhpDoc::text(
'Create the default operation client for the service.',
),
PhpDoc::param(
AST::param(ResolvedType::array(), $options),
PhpDoc::text('ClientOptions for the client.')
),
PhpDoc::return($operationsClientType)
));
$methods = $methods->append($createOperationsClient);
if ($this->serviceDetails->hasCustomOp) {
$operationsClientType = $this->ctx->type($this->serviceDetails->customOperationServiceClientType);
$createOperationsClient = AST::method('createOperationsClient')
->withAccess(Access::PRIVATE)
->withParams(AST::param(ResolvedType::array(), $options))
->withReturnType($operationsClientType)
->withBody(AST::block(
'// Unset client-specific configuration options',
AST::call(AST::method('unset'))(
AST::index($options, 'serviceName'),
AST::index($options, 'clientConfig'),
AST::index($options, 'descriptorsConfigPath'),
),
PHP_EOL,
AST::if(
AST::call(AST::method('isset'))(AST::index($options, 'operationsClient'))
)->then(AST::return(AST::index($options, 'operationsClient'))),
PHP_EOL,
AST::return(AST::new($operationsClientType)($options))
))
->withPhpDoc(PhpDoc::block(
PhpDoc::text(
'Create the default operation client for the service.',
),
PhpDoc::param(
AST::param(ResolvedType::array(), $options),
PhpDoc::text('ClientOptions for the client.')
),
PhpDoc::return($operationsClientType)
));
$methods = $methods->append($createOperationsClient);
}

return $methods;
}
Expand Down Expand Up @@ -498,13 +522,6 @@ private function getClientDefaults(): PhpClassMember
'descriptorsConfigPath' => AST::concat(AST::__DIR__, "/../resources/$descriptorConfigFilename"),
];

// TODO: Consolidate setting all the known array values together.
// We do this here to maintain the existing sensible ordering.
if ($this->serviceDetails->transportType !== Transport::REST) {
$clientDefaultValues['gcpApiConfigPath'] =
AST::concat(AST::__DIR__, "/../resources/{$this->serviceDetails->grpcConfigFilename}");
}

$credentialsConfig = [
'defaultScopes' => AST::access(AST::SELF, $this->serviceScopes()),
];
Expand All @@ -524,6 +541,7 @@ private function getClientDefaults(): PhpClassMember

return AST::method('getClientDefaults')
->withAccess(Access::PRIVATE, Access::STATIC)
->withReturnType(ResolvedType::array())
->withBody(AST::block(
AST::return(AST::array($clientDefaultValues))
));
Expand All @@ -537,6 +555,7 @@ private function defaultTransport()
return AST::method('defaultTransport')
->withPhpDocText('Implements GapicClientTrait::defaultTransport.')
->withAccess(Access::PRIVATE, Access::STATIC)
->withReturnType(ResolvedType::string())
->withBody(AST::block(
AST::return(AST::literal("'rest'"))
));
Expand All @@ -548,6 +567,7 @@ private function supportedTransports()
return AST::method('supportedTransports')
->withPhpDocText('Implements ClientOptionsTrait::supportedTransports.')
->withAccess(Access::PRIVATE, Access::STATIC)
->withReturnType(ResolvedType::array())
->withBody(AST::block(
AST::return(AST::array(['rest']))
));
Expand All @@ -557,6 +577,7 @@ private function supportedTransports()
return AST::method('supportedTransports')
->withPhpDocText('Implements ClientOptionsTrait::supportedTransports.')
->withAccess(Access::PRIVATE, Access::STATIC)
->withReturnType(ResolvedType::array())
->withBody(AST::block(
AST::return(AST::array(['grpc', 'grpc-fallback']))
));
Expand Down Expand Up @@ -678,14 +699,14 @@ private function construct(): PhpClassMember
PhpDoc::type(
Vector::new([
$ctx->type(Type::fromName(FetchAuthTokenInterface::class)),
$ctx->type(Type::fromName(CredentialsWrapper::class))
$ctx->type(Type::fromName(HeaderCredentialsInterface::class))
]),
'credentials',
PhpDoc::text(
'This option should only be used with a pre-constructed',
$ctx->type(Type::fromName(FetchAuthTokenInterface::class)),
'or',
$ctx->type(Type::fromName(CredentialsWrapper::class)),
$ctx->type(Type::fromName(HeaderCredentialsInterface::class)),
'object. Note that when one of these objects are provided, any settings in $credentialsConfig',
'will be ignored.',
PhpDoc::newLine(),
Expand Down
Loading
Loading