This repository has been archived by the owner on Jun 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 129
/
client_impl.snip
640 lines (590 loc) · 21.7 KB
/
client_impl.snip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
@extends "php/common.snip"
@extends "php/method_sample.snip"
@snippet generate(xapiClass)
{@renderFileHeader(xapiClass.fileHeader, generatedCodeWarning(xapiClass))}
{@serviceDoc(xapiClass)}
class {@xapiClass.name}
{
{@traits()}
{@constants(xapiClass)}
{@statics(xapiClass)}
{@members(xapiClass)}
{@staticFunctions(xapiClass)}
{@functions(xapiClass)}
{@constructor(xapiClass)}
{@apiMethods(xapiClass)}
}
@end
@private generatedCodeWarning(xapiClass)
/*
* GENERATED CODE WARNING
* This file was generated from the file
* https://github.com/google/googleapis/blob/master/{@xapiClass.protoFilename}
* and updates to that file get reflected here through a refresh process.
*
* @@experimental
*/
@end
@private serviceDoc(xapiClass)
@let coreSampleCode = sampleCode(xapiClass.doc.exampleApiMethod), \
decoratedSampleCode = decorateSampleCode(xapiClass, xapiClass.doc.exampleApiMethod, coreSampleCode)
{@renderServiceDoc(xapiClass.doc, decoratedSampleCode, xapiClass.hasFormatOrParseResourceFunctions)}
@end
@end
@private renderServiceDoc(xapiClassDoc, exampleMethodSampleCode, hasFormatOrParseResourceFunctions)
/**
* Service Description: {@xapiClassDoc.firstLine}
@if xapiClassDoc.remainingLines
@join commentLine : xapiClassDoc.remainingLines
{@""} * {@commentLine}
@end
@end
*
* This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* ```
@join sampleLine : util.getDocLines(exampleMethodSampleCode)
{@""} * {@sampleLine}
@end
* ```
*
@if hasFormatOrParseResourceFunctions
{@""} * Many parameters require resource names to be formatted in a particular way. To assist
* with these names, this class includes a format method for each type of name, and additionally
* a parseName method to extract the individual identifiers contained within formatted names
* that are returned by the API.
@end
* @@experimental
*/
@end
@private traits()
use GapicClientTrait;
@end
@private constants(xapiClass)
/**
* The name of the service.
*/
const SERVICE_NAME = '{@xapiClass.interfaceKey}';
@if xapiClass.hasDefaultServiceAddress
/**
* The default address of the service.
*/
const SERVICE_ADDRESS = '{@xapiClass.serviceHostname}';
@end
/**
* The default port of the service.
*/
const DEFAULT_SERVICE_PORT = {@xapiClass.servicePort};
/**
* The name of the code generator, to be included in the agent header.
*/
const CODEGEN_NAME = 'gapic';
@if xapiClass.hasDefaultServiceScopes
/**
* The default scopes required by the service.
*/
public static $serviceScopes = [
@join scope : {@xapiClass.authScopes}
'{@scope}',
@end
];
@end
@end
@private statics(xapiClass)
@join pathTemplate : xapiClass.pathTemplates
private static ${@pathTemplate.name};
@end
{@""}
@if xapiClass.hasFormatOrParseResourceFunctions
private static $pathTemplateMap;
@end
{@""}
@end
@private members(xapiClass)
@if xapiClass.hasLongRunningOperations
private $operationsClient;
@end
{@""}
@end
@private staticFunctions(xapiClass)
private static function getClientDefaults()
{
return [
'serviceName' => self::SERVICE_NAME,
@if xapiClass.hasDefaultServiceAddress
'serviceAddress' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT,
@end
'clientConfig' => __DIR__ . '{@xapiClass.clientConfigPath}',
'descriptorsConfigPath' => __DIR__ . '/../resources/{@xapiClass.clientConfigName}_descriptor_config.php',
@if xapiClass.supportsGrpcTransport
'gcpApiConfigPath' => __DIR__ . '/../resources/{@xapiClass.clientConfigName}_grpc_config.json',
@end
'credentialsConfig' => [
@if xapiClass.hasDefaultServiceScopes
'defaultScopes' => self::$serviceScopes,
@end
],
'transportConfig' => [
'rest' => [
'restClientConfigPath' => __DIR__ . '/../resources/{@xapiClass.clientConfigName}_rest_client_config.php',
]
]
];
}
@join function : xapiClass.pathTemplateGetterFunctions
{@pathTemplateGetterFunction(function)}
@end
{@pathTemplateMapFunction(xapiClass)}
@join function : xapiClass.formatResourceFunctions
{@formatResourceFunction(function)}
@end
@if xapiClass.hasFormatOrParseResourceFunctions
{@parseNameFunction(xapiClass)}
@end
@if not(xapiClass.supportsGrpcTransport)
private static function defaultTransport()
{
return 'rest';
}
private static function getSupportedTransports()
{
return ['rest'];
}
@end
{@""}
@end
@private formatResourceFunction(function)
/**
* Formats a string containing the fully-qualified path to represent
* a {@function.entityName} resource.
*
@join param : function.resourceIdParams
{@""} * @@param string ${@param.name}
@end
* @@return string The formatted {@function.entityName} resource.
@if function.isResourceNameDeprecated
{@""} * @@deprecated Multi-pattern resource names will have unified formatting functions.
{@""} * This helper function will be deleted in the next major version.
@else
{@""} * @@experimental
@end
*/
public static function {@function.name}(\
{@formatResourceFunctionParams(function.resourceIdParams)})
{
return self::{@function.pathTemplateGetterName}()->render([
{@pathTemplateArgs(function.resourceIdParams)},
]);
}
{@""}
@end
@private formatResourceFunctionParams(resourceIdParams)
@join param : resourceIdParams on ", "
${@param.name}
@end
@end
@private parseNameFunction(xapiClass)
/**
* Parses a formatted name string and returns an associative array of the components in the name.
* The following name formats are supported:
* Template: Pattern
@join function : xapiClass.pathTemplateGetterFunctions
{@""} * - {@function.entityName}: {@function.pattern}
@end
*
* The optional $template argument can be supplied to specify a particular pattern, and must
* match one of the templates listed above. If no $template argument is provided, or if the
* $template argument does not match one of the templates listed, then parseName will check
* each of the supported templates, and return the first match.
*
* @@param string $formattedName The formatted name string
* @@param string $template Optional name of template to match
* @@return array An associative array from name component IDs to component values.
* @@throws ValidationException If $formattedName could not be matched.
* @@experimental
*/
public static function parseName($formattedName, $template = null)
{
$templateMap = self::getPathTemplateMap();
if ($template) {
if (!isset($templateMap[$template])) {
throw new ValidationException("Template name $template does not exist");
}
return $templateMap[$template]->match($formattedName);
}
foreach ($templateMap as $templateName => $pathTemplate) {
try {
return $pathTemplate->match($formattedName);
} catch (ValidationException $ex) {
// Swallow the exception to continue trying other path templates
}
}
throw new ValidationException("Input did not match any known format. Input: $formattedName");
}
{@""}
@end
@private pathTemplateArgs(resourceIdParams)
@join param : resourceIdParams on ",".add(BREAK)
'{@param.templateKey}' => ${@param.name}
@end
@end
@private pathTemplateGetterFunction(function)
private static function {@function.name}()
{
if (self::${@function.pathTemplateName} == null) {
self::${@function.pathTemplateName} = new PathTemplate('{@function.pattern}');
}
return self::${@function.pathTemplateName};
}
{@""}
@end
@private pathTemplateMapFunction(xapiClass)
@if xapiClass.hasFormatOrParseResourceFunctions
{@""}
private static function getPathTemplateMap()
{
if (self::$pathTemplateMap == null) {
self::$pathTemplateMap = [
@join function : xapiClass.pathTemplateGetterFunctions
'{@function.entityName}' => self::{@function.name}(),
@end
];
}
return self::$pathTemplateMap;
}
@end
@end
@private functions(xapiClass)
@if xapiClass.hasLongRunningOperations
/**
* Return an OperationsClient object with the same endpoint as $this.
*
* @@return OperationsClient
* @@experimental
*/
public function getOperationsClient()
{
return $this->operationsClient;
}
/**
* Resume an existing long running operation that was previously started
* by a long running API method. If $methodName is not provided, or does
* not match a long running API method, then the operation can still be
* resumed, but the OperationResponse object will not deserialize the
* final response.
*
* @@param string $operationName The name of the long running operation
* @@param string $methodName The name of the method used to start the operation
* @@return OperationResponse
* @@experimental
*/
public function resumeOperation($operationName, $methodName = null)
{
$options = isset($this->descriptors[$methodName]['longRunning'])
? $this->descriptors[$methodName]['longRunning']
: [];
$operation = new OperationResponse($operationName, $this->getOperationsClient(), $options);
$operation->reload();
return $operation;
}
@end
{@""}
@end
@private constructor(xapiClass)
/**
* Constructor.
*
* @@param array $options {
@if xapiClass.hasMissingDefaultOptions
* Required. Options for configuring the service API wrapper. Those options
* that must be provided are marked as Required.
@else
* Optional. Options for configuring the service API wrapper.
@end
@if xapiClass.hasDefaultServiceAddress
* @@type string $serviceAddress
* The address of the API remote host. May optionally include the port, formatted
* as "<uri>:<port>". Default '{@xapiClass.serviceHostname}:{@xapiClass.servicePort}'.
@else
* @@type string $serviceAddress
* Required. The address of the API remote host. May optionally include the port,
* formatted as "<uri>:<port>".
@end
* @@type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials
* The credentials to be used by the client to authorize API calls. This option
* accepts either a path to a credentials file, or a decoded credentials file as a
* PHP array.
* *Advanced usage*: In addition, this option can also accept a pre-constructed
* {@@see \Google\Auth\FetchAuthTokenInterface} object or
* {@@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these
* objects are provided, any settings in $credentialsConfig will be ignored.
* @@type array $credentialsConfig
* Options used to configure credentials, including auth token caching, for the client.
* For a full list of supporting configuration options, see
* {@@see \Google\ApiCore\CredentialsWrapper::build()}.
* @@type bool $disableRetries
* Determines whether or not retries defined by the client configuration should be
* disabled. Defaults to `false`.
* @@type string|array $clientConfig
* Client method configuration, including retry settings. This option can be either a
* path to a JSON file, or a PHP array containing the decoded JSON data.
* By default this settings points to the default client config file, which is provided
* in the resources folder.
@if xapiClass.supportsGrpcTransport
* @@type string|TransportInterface $transport
* The transport used for executing network requests. May be either the string `rest`
* or `grpc`. Defaults to `grpc` if gRPC support is detected on the system.
* *Advanced usage*: Additionally, it is possible to pass in an already instantiated
* {@@see \Google\ApiCore\Transport\TransportInterface} object. Note that when this
* object is provided, any settings in $transportConfig, and any $serviceAddress
* setting, will be ignored.
* @@type array $transportConfig
* Configuration options that will be used to construct the transport. Options for
* each supported transport type should be passed in a key for that transport. For
* example:
* $transportConfig = [
* 'grpc' => [...],
* 'rest' => [...]
* ];
* See the {@@see \Google\ApiCore\Transport\GrpcTransport::build()} and
* {@@see \Google\ApiCore\Transport\RestTransport::build()} methods for the
* supported options.
@else
* @@type string|TransportInterface $transport
* The transport used for executing network requests. At the moment, only supports
* `rest`.
* *Advanced usage*: Additionally, it is possible to pass in an already instantiated
* {@@see \Google\ApiCore\Transport\TransportInterface} object. Note that when this
* object is provided, any settings in $transportConfig, and any $serviceAddress
* setting, will be ignored.
* @@type array $transportConfig
* Configuration options that will be used to construct the transport. Options for
* each supported transport type should be passed in a key for that transport. For
* example:
* $transportConfig = [
* 'rest' => [...]
* ];
* See the {@@see \Google\ApiCore\Transport\RestTransport::build()} method for the
* supported options.
@end
* }
* @@throws ValidationException
* @@experimental
*/
public function __construct(array $options = [])
{
$clientOptions = $this->buildClientOptions($options);
$this->setClientOptions($clientOptions);
@if xapiClass.hasLongRunningOperations
$this->operationsClient = $this->createOperationsClient($clientOptions);
@end
}
{@""}
@end
@private apiMethods(xapiClass)
@join apiMethod : xapiClass.apiMethods
@let coreSampleCode = sampleCode(apiMethod)
{@methodDoc(apiMethod.doc, decorateSampleCode(xapiClass, apiMethod, coreSampleCode))}
@end
public function {@apiMethod.name}({@paramList(apiMethod.methodParams)})
{
@if apiMethod.isSingularRequestMethod
$request = new {@apiMethod.requestTypeName}();
@join param : apiMethod.requiredRequestObjectParams
{@setRequiredFieldCall(param)}
@end
@join param : apiMethod.optionalRequestObjectParams
{@setOptionalFieldCall(param)}
@end
@end
@if @apiMethod.headerRequestParams
{@requestParams(apiMethod.headerRequestParams)}
@end
{@setCall(apiMethod)}
}
{@""}
@end
@end
@private setCall(apiMethod)
@switch apiMethod.type.toString
@case "PagedOptionalArrayMethod"
return $this->getPagedListResponse(
'{@apiMethod.grpcMethodName}',
$optionalArgs,
{@apiMethod.responseTypeName}::class,
@if apiMethod.hasRerouteToGrpcInterface
$request,
'{@apiMethod.rerouteToGrpcInterface}'
@else
$request
@end
);
@case "LongRunningOptionalArrayMethod"
return $this->startOperationsCall(
'{@apiMethod.grpcMethodName}',
$optionalArgs,
$request,
@if apiMethod.hasRerouteToGrpcInterface
$this->getOperationsClient(),
'{@apiMethod.rerouteToGrpcInterface}'
@else
$this->getOperationsClient()
@end
)->wait();
@case "OptionalArrayMethod"
return $this->startCall(
'{@apiMethod.grpcMethodName}',
{@apiMethod.responseTypeName}::class,
$optionalArgs,
@if apiMethod.isGrpcStreamingMethod
@if apiMethod.isSingularRequestMethod
$request,
@else
null,
@end
@if apiMethod.hasRerouteToGrpcInterface
{@streamingCallType(apiMethod)},
'{@apiMethod.rerouteToGrpcInterface}'
@else
{@streamingCallType(apiMethod)}
@end
);
@else
@if apiMethod.hasRerouteToGrpcInterface
$request,
Call::UNARY_CALL,
'{@apiMethod.rerouteToGrpcInterface}'
@else
$request
@end
)->wait();
@end
@end
@end
@private streamingCallType(apiMethod)
@switch apiMethod.grpcStreamingType.toString
@case "BidiStreaming"
Call::BIDI_STREAMING_CALL
@case "ClientStreaming"
Call::CLIENT_STREAMING_CALL
@case "ServerStreaming"
Call::SERVER_STREAMING_CALL
@end
@end
@private requestParams(headerRequestParams)
$requestParams = new RequestParamsHeaderDescriptor([
@join headerRequestParam : @headerRequestParams
'{@headerRequestParam.fullyQualifiedName}' => $request->{@requestParamGetter(headerRequestParam.gettersChain)},
@end
]);
$optionalArgs['headers'] = isset($optionalArgs['headers'])
? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
: $requestParams->getHeader();
@end
@private requestParamGetter(gettersChain)
@join getter : gettersChain on "->"
{@getter}()
@end
@end
@private paramList(params)
@join param : params on ", "
@if param.defaultValue
{@paramDeclaration(param)} = {@param.defaultValue}
@else
{@paramDeclaration(param)}
@end
@end
@end
@private paramDeclaration(param)
@if param.hasTypeHint
{@param.typeHint} ${@param.name}
@else
${@param.name}
@end
@end
@private setRequiredFieldCall(param)
$request->{@param.setCallName}(${@param.name});
@end
@private setOptionalFieldCall(param)
if (isset($optionalArgs['{@param.name}'])) {
$request->{@param.setCallName}($optionalArgs['{@param.name}']);
}
@end
@private methodDoc(apiMethodDoc, methodSampleCode)
/**
@if apiMethodDoc.mainDocLines
@join commentLine : apiMethodDoc.mainDocLines
{@""} * {@commentLine}
@end
@else
{@""} *
@end
*
* Sample code:
* ```
@join sampleLine : util.getDocLines(methodSampleCode)
{@""} * {@sampleLine}
@end
* ```
@if apiMethodDoc.paramDocs
{@""} *
@join doc : apiMethodDoc.paramDocs
{@paramDoc(doc)}
@end
@end
@if apiMethodDoc.returnTypeName
{@""} *
* @@return {@apiMethodDoc.returnTypeName}
@end
*
* @@throws ApiException if the remote call fails
* @@experimental
*/
{@""}
@end
@private paramDoc(doc)
@switch doc.type
@case "SimpleParamDocView"
{@simpleParamDoc(doc)}
@case "MapParamDocView"
{@mapParamDoc(doc)}
@default
$unhandledCase: {@doc.type}$
@end
@end
@private simpleParamDoc(doc)
@if doc.lines
{@""} * @@param {@doc.typeName} ${@doc.paramName} {@doc.firstLine}
@if doc.remainingLines
@join commentLine : doc.remainingLines
{@""} * {@commentLine}
@end
@end
@else
{@""} * @@param {@doc.typeName} ${@doc.paramName}
@end
@end
@private mapParamDoc(doc)
{@""} * @@param {@doc.typeName} ${@doc.paramName} {
* {@doc.firstLine}
@if doc.remainingLines
@join commentLine : doc.remainingLines
{@""} * {@commentLine}
@end
@end
@if doc.arrayKeyDocs
@join simpleParamDoc : doc.arrayKeyDocs
{@""} * @@type {@simpleParamDoc.typeName} ${@simpleParamDoc.paramName}
@if simpleParamDoc.lines
{@""} * {@simpleParamDoc.firstLine}
@if simpleParamDoc.remainingLines
@join commentLine : simpleParamDoc.remainingLines
{@""} * {@commentLine}
@end
@end
@end
@end
@end
* }
@end