Skip to content

Commit 1cf60ae

Browse files
authored
Do not inject InvalidArgument class when not needed (#1608)
1 parent c4a7cfb commit 1cf60ae

File tree

12 files changed

+230
-51
lines changed

12 files changed

+230
-51
lines changed

src/CodeGenerator/src/Generator/InputGenerator.php

+23-12
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,6 @@ public function generate(Operation $operation): ClassName
296296
$classBuilder->addUse(StreamFactory::class);
297297
$this->inputClassRequestGetters($shape, $classBuilder, $operation);
298298

299-
$classBuilder->addUse(InvalidArgument::class);
300299
$this->addUse($shape, $classBuilder);
301300

302301
$classBuilder->addExtend(Input::class);
@@ -305,12 +304,14 @@ public function generate(Operation $operation): ClassName
305304
return $className;
306305
}
307306

308-
private function inputClassRequestPartGettersEnumGenerator(Member $member, string $requestPart, string $input): string
307+
private function inputClassRequestPartGettersEnumGenerator(Member $member, ClassBuilder $classBuilder, string $requestPart, string $input): string
309308
{
310309
$memberShape = $member->getShape();
311310
$validateEnum = '';
312311
if (!empty($memberShape->getEnum())) {
313312
$enumClassName = $this->namespaceRegistry->getEnum($memberShape);
313+
$classBuilder->addUse(InvalidArgument::class);
314+
314315
$validateEnum = strtr('if (!ENUM_CLASS::exists(VALUE)) {
315316
throw new InvalidArgument(sprintf(\'Invalid parameter "MEMBER_NAME" for "%s". The value "%s" is not a valid "ENUM_CLASS".\', __CLASS__, INPUT));
316317
}', [
@@ -343,7 +344,7 @@ private function inputClassRequestPartGettersHookGenerator(StructureMember $memb
343344
]);
344345
}
345346

346-
private function inputClassRequestPartGetters(StructureMember $member, Operation $operation, string $requestPart, string $input, string $output): string
347+
private function inputClassRequestPartGetters(StructureMember $member, ClassBuilder $classBuilder, Operation $operation, string $requestPart, string $input, string $output): string
347348
{
348349
$memberShape = $member->getShape();
349350
if ($memberShape instanceof ListShape) {
@@ -365,7 +366,7 @@ private function inputClassRequestPartGetters(StructureMember $member, Operation
365366
'INPUT' => $input,
366367
'OUTPUT' => $output,
367368
'VALUE' => $this->stringify('$value', $memberShape->getMember(), $requestPart),
368-
'VALIDATE_ENUM' => $this->inputClassRequestPartGettersEnumGenerator($memberShape->getMember(), $requestPart, '$value'),
369+
'VALIDATE_ENUM' => $this->inputClassRequestPartGettersEnumGenerator($memberShape->getMember(), $classBuilder, $requestPart, '$value'),
369370
'APPLY_HOOK' => $this->inputClassRequestPartGettersHookGenerator($member, $operation, $requestPart, $input),
370371
]);
371372
}
@@ -376,7 +377,7 @@ private function inputClassRequestPartGetters(StructureMember $member, Operation
376377
OUTPUT = VALUE;';
377378

378379
return strtr($bodyCode, [
379-
'VALIDATE_ENUM' => $this->inputClassRequestPartGettersEnumGenerator($member, $requestPart, $input),
380+
'VALIDATE_ENUM' => $this->inputClassRequestPartGettersEnumGenerator($member, $classBuilder, $requestPart, $input),
380381
'APPLY_HOOK' => $this->inputClassRequestPartGettersHookGenerator($member, $operation, $requestPart, $input),
381382
'OUTPUT' => $output,
382383
'VALUE' => $this->stringify($input, $member, $requestPart),
@@ -414,6 +415,7 @@ private function inputClassRequestGetters(StructureShape $inputShape, ClassBuild
414415
}
415416

416417
if ($member->isRequired()) {
418+
$classBuilder->addUse(InvalidArgument::class);
417419
$bodyCode = 'if (null === $v = $this->PROPERTY) {
418420
throw new InvalidArgument(sprintf(\'Missing parameter "MEMBER_NAME" for "%s". The value cannot be null.\', __CLASS__));
419421
}
@@ -429,7 +431,7 @@ private function inputClassRequestGetters(StructureShape $inputShape, ClassBuild
429431
}
430432

431433
$bodyCode = strtr(strtr($bodyCode, [
432-
'GETTER_CODE' => $this->inputClassRequestPartGetters($member, $operation, $requestPart, $input, $output),
434+
'GETTER_CODE' => $this->inputClassRequestPartGetters($member, $classBuilder, $operation, $requestPart, $input, $output),
433435
]), [
434436
'MEMBER_NAME' => $member->getName(),
435437
'VAR_NAME' => $varName,
@@ -478,14 +480,23 @@ private function inputClassRequestGetters(StructureShape $inputShape, ClassBuild
478480
}
479481

480482
if ($operation->hasBody()) {
481-
[$body['body'], $hasRequestBody, $overrideArgs] = $serializer->generateRequestBody($operation, $inputShape) + [null, null, []];
482-
if ($hasRequestBody) {
483-
[$returnType, $requestBody, $args] = $serializer->generateRequestBuilder($inputShape, true) + [null, null, []];
484-
if ('' === trim($requestBody)) {
483+
$serializerBodyResult = $serializer->generateRequestBody($operation, $inputShape);
484+
$body['body'] = $serializerBodyResult->getBody();
485+
foreach ($serializerBodyResult->getUsedClasses() as $classNameFqdn) {
486+
$classBuilder->addUse($classNameFqdn);
487+
}
488+
489+
if ($serializerBodyResult->hasRequestBody()) {
490+
$serializerBuilderResult = $serializer->generateRequestBuilder($inputShape, true);
491+
foreach ($serializerBuilderResult->getUsedClasses() as $classNameFqdn) {
492+
$classBuilder->addUse($classNameFqdn);
493+
}
494+
495+
if ('' === trim($serializerBuilderResult->getBody())) {
485496
$body['body'] = '$body = "";';
486497
} else {
487-
$method = $classBuilder->addMethod('requestBody')->setReturnType($returnType)->setBody($requestBody)->setPrivate();
488-
foreach ($overrideArgs + $args as $arg => $type) {
498+
$method = $classBuilder->addMethod('requestBody')->setReturnType($serializerBuilderResult->getReturnType())->setBody($serializerBuilderResult->getBody())->setPrivate();
499+
foreach ($serializerBodyResult->getExtraMethodArgs() + $serializerBuilderResult->getExtraMethodArgs() as $arg => $type) {
489500
$method->addParameter($arg)->setType($type);
490501
}
491502
}

src/CodeGenerator/src/Generator/ObjectGenerator.php

+7-5
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,17 @@ public function generate(StructureShape $shape, bool $forEndpoint = false): Clas
106106

107107
$serializer = $this->serializer->get($shape->getService());
108108
if ($this->isShapeUsedInput($shape)) {
109-
[$returnType, $requestBody, $args] = $serializer->generateRequestBuilder($shape, false) + [null, null, []];
110-
$method = $classBuilder->addMethod('requestBody')->setReturnType($returnType)->setBody($requestBody)->setPublic()->setComment('@internal');
111-
foreach ($args as $arg => $type) {
109+
$serializerBuilderResult = $serializer->generateRequestBuilder($shape, false);
110+
foreach ($serializerBuilderResult->getUsedClasses() as $classNameFqdn) {
111+
$classBuilder->addUse($classNameFqdn);
112+
}
113+
114+
$method = $classBuilder->addMethod('requestBody')->setReturnType($serializerBuilderResult->getReturnType())->setBody($serializerBuilderResult->getBody())->setPublic()->setComment('@internal');
115+
foreach ($serializerBuilderResult->getExtraMethodArgs() as $arg => $type) {
112116
$method->addParameter($arg)->setType($type);
113117
}
114118
}
115119

116-
$classBuilder->addUse(InvalidArgument::class);
117-
118120
return $className;
119121
}
120122

src/CodeGenerator/src/Generator/RequestSerializer/QuerySerializer.php

+19-10
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use AsyncAws\CodeGenerator\Generator\Composer\RequirementsRegistry;
1515
use AsyncAws\CodeGenerator\Generator\GeneratorHelper;
1616
use AsyncAws\CodeGenerator\Generator\Naming\NamespaceRegistry;
17+
use AsyncAws\Core\Exception\InvalidArgument;
1718

1819
/**
1920
* Serialize a request body to a flattened array with "." as separator.
@@ -24,6 +25,8 @@
2425
*/
2526
class QuerySerializer implements Serializer
2627
{
28+
use UseClassesTrait;
29+
2730
/**
2831
* @var NamespaceRegistry
2932
*/
@@ -45,10 +48,12 @@ public function getHeaders(Operation $operation): string
4548
return '["content-type" => "application/x-www-form-urlencoded"]';
4649
}
4750

48-
public function generateRequestBody(Operation $operation, StructureShape $shape): array
51+
public function generateRequestBody(Operation $operation, StructureShape $shape): SerializerResultBody
4952
{
53+
$this->usedClassesInit();
5054
if (null !== $payloadProperty = $shape->getPayload()) {
5155
if ($shape->getMember($payloadProperty)->isRequired()) {
56+
$this->usedClassesAdd(InvalidArgument::class);
5257
$body = 'if (null === $v = $this->PROPERTY) {
5358
throw new InvalidArgument(sprintf(\'Missing parameter "NAME" for "%s". The value cannot be null.\', __CLASS__));
5459
}
@@ -57,20 +62,21 @@ public function generateRequestBody(Operation $operation, StructureShape $shape)
5762
$body = '$body = $this->PROPERTY ?? "";';
5863
}
5964

60-
return [strtr($body, [
65+
return new SerializerResultBody(strtr($body, [
6166
'PROPERTY' => GeneratorHelper::normalizeName($payloadProperty),
6267
'NAME' => $payloadProperty,
63-
]), false];
68+
]), false, $this->usedClassesFlush());
6469
}
6570

66-
return [strtr('$body = http_build_query([\'Action\' => OPERATION_NAME, \'Version\' => API_VERSION] + $this->requestBody(), \'\', \'&\', \PHP_QUERY_RFC1738);', [
71+
return new SerializerResultBody(strtr('$body = http_build_query([\'Action\' => OPERATION_NAME, \'Version\' => API_VERSION] + $this->requestBody(), \'\', \'&\', \PHP_QUERY_RFC1738);', [
6772
'OPERATION_NAME' => var_export($operation->getName(), true),
6873
'API_VERSION' => var_export($operation->getApiVersion(), true),
69-
]), true];
74+
]), true, $this->usedClassesFlush());
7075
}
7176

72-
public function generateRequestBuilder(StructureShape $shape, bool $needsChecks): array
77+
public function generateRequestBuilder(StructureShape $shape, bool $needsChecks): SerializerResultBuilder
7378
{
79+
$this->usedClassesInit();
7480
$body = implode("\n", array_map(function (StructureMember $member) use ($needsChecks) {
7581
if (null !== $member->getLocation()) {
7682
return '';
@@ -85,6 +91,7 @@ public function generateRequestBuilder(StructureShape $shape, bool $needsChecks)
8591
$inputElement = '$v';
8692
} elseif ($member->isRequired()) {
8793
if ($needsChecks) {
94+
$this->usedClassesAdd(InvalidArgument::class);
8895
$body = 'if (null === $v = $this->PROPERTY) {
8996
throw new InvalidArgument(sprintf(\'Missing parameter "NAME" for "%s". The value cannot be null.\', __CLASS__));
9097
}
@@ -113,14 +120,14 @@ public function generateRequestBuilder(StructureShape $shape, bool $needsChecks)
113120
]);
114121
}, $shape->getMembers()));
115122

116-
return ['array', strtr('
123+
return new SerializerResultBuilder('array', strtr('
117124
$payload = [];
118125
CHILDREN_CODE
119126
120127
return $payload;
121128
', [
122129
'CHILDREN_CODE' => $body,
123-
])];
130+
]), $this->usedClassesFlush());
124131
}
125132

126133
private function getQueryName(Member $member, string $default): string
@@ -206,6 +213,7 @@ private function dumpArrayMap(string $output, string $input, string $contextProp
206213
$mapKeyShape = $shape->getKey()->getShape();
207214
if (!empty($mapKeyShape->getEnum())) {
208215
$enumClassName = $this->namespaceRegistry->getEnum($mapKeyShape);
216+
$this->usedClassesAdd(InvalidArgument::class);
209217
$validateEnum = strtr('if (!ENUM_CLASS::exists($mapKey)) {
210218
throw new InvalidArgument(sprintf(\'Invalid key for "%s". The value "%s" is not a valid "ENUM_CLASS".\', __CLASS__, $mapKey));
211219
}', [
@@ -228,7 +236,7 @@ private function dumpArrayMap(string $output, string $input, string $contextProp
228236
'INPUT' => $input,
229237
'VALIDATE_ENUM' => $validateEnum,
230238
'OUTPUT_KEY' => sprintf('%s.$index.%s', $output, $this->getQueryName($shape->getKey(), 'key')),
231-
'MEMBER_CODE' => $memberCode = $this->dumpArrayElement(sprintf('%s.$index.%s', $output, $this->getQueryName($shape->getValue(), 'value')), '$mapValue', $contextProperty, $shape->getValue()->getShape()),
239+
'MEMBER_CODE' => $this->dumpArrayElement(sprintf('%s.$index.%s', $output, $this->getQueryName($shape->getValue(), 'value')), '$mapValue', $contextProperty, $shape->getValue()->getShape()),
232240
]);
233241
}
234242

@@ -245,7 +253,7 @@ private function dumpArrayList(string $output, string $input, string $contextPro
245253
',
246254
[
247255
'INPUT' => $input,
248-
'MEMBER_CODE' => $memberCode = $this->dumpArrayElement(sprintf('%s.$index', $output), '$mapValue', $contextProperty, $memberShape),
256+
'MEMBER_CODE' => $this->dumpArrayElement(sprintf('%s.$index', $output), '$mapValue', $contextProperty, $memberShape),
249257
]);
250258
}
251259

@@ -258,6 +266,7 @@ private function dumpArrayScalar(string $output, string $input, string $contextP
258266
];
259267
if (!empty($shape->getEnum())) {
260268
$enumClassName = $this->namespaceRegistry->getEnum($shape);
269+
$this->usedClassesAdd(InvalidArgument::class);
261270
$body = 'if (!ENUM_CLASS::exists(INPUT)) {
262271
throw new InvalidArgument(sprintf(\'Invalid parameter "PROPERTY" for "%s". The value "%s" is not a valid "ENUM_CLASS".\', __CLASS__, INPUT));
263272
}

src/CodeGenerator/src/Generator/RequestSerializer/RestJsonSerializer.php

+16-7
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use AsyncAws\CodeGenerator\Generator\Composer\RequirementsRegistry;
1515
use AsyncAws\CodeGenerator\Generator\GeneratorHelper;
1616
use AsyncAws\CodeGenerator\Generator\Naming\NamespaceRegistry;
17+
use AsyncAws\Core\Exception\InvalidArgument;
1718

1819
/**
1920
* Serialize a request body to a nice nested array.
@@ -24,6 +25,8 @@
2425
*/
2526
class RestJsonSerializer implements Serializer
2627
{
28+
use UseClassesTrait;
29+
2730
/**
2831
* @var NamespaceRegistry
2932
*/
@@ -45,10 +48,12 @@ public function getHeaders(Operation $operation): string
4548
return '["content-type" => "application/json"]';
4649
}
4750

48-
public function generateRequestBody(Operation $operation, StructureShape $shape): array
51+
public function generateRequestBody(Operation $operation, StructureShape $shape): SerializerResultBody
4952
{
53+
$this->usedClassesInit();
5054
if (null !== $payloadProperty = $shape->getPayload()) {
5155
if ($shape->getMember($payloadProperty)->isRequired()) {
56+
$this->usedClassesAdd(InvalidArgument::class);
5257
$body = 'if (null === $v = $this->PROPERTY) {
5358
throw new InvalidArgument(sprintf(\'Missing parameter "NAME" for "%s". The value cannot be null.\', __CLASS__));
5459
}
@@ -57,19 +62,20 @@ public function generateRequestBody(Operation $operation, StructureShape $shape)
5762
$body = '$body = $this->PROPERTY ?? "";';
5863
}
5964

60-
return [strtr($body, [
65+
return new SerializerResultBody(strtr($body, [
6166
'PROPERTY' => GeneratorHelper::normalizeName($payloadProperty),
6267
'NAME' => $payloadProperty,
63-
]), false];
68+
]), false, $this->usedClassesFlush());
6469
}
6570

6671
$this->requirementsRegistry->addRequirement('ext-json');
6772

68-
return ['$bodyPayload = $this->requestBody(); $body = empty($bodyPayload) ? "{}" : \json_encode($bodyPayload, ' . \JSON_THROW_ON_ERROR . ');', true];
73+
return new SerializerResultBody('$bodyPayload = $this->requestBody(); $body = empty($bodyPayload) ? "{}" : \json_encode($bodyPayload, ' . \JSON_THROW_ON_ERROR . ');', true, $this->usedClassesFlush());
6974
}
7075

71-
public function generateRequestBuilder(StructureShape $shape, bool $needsChecks): array
76+
public function generateRequestBuilder(StructureShape $shape, bool $needsChecks): SerializerResultBuilder
7277
{
78+
$this->usedClassesInit();
7379
$body = implode("\n", array_map(function (StructureMember $member) use ($needsChecks) {
7480
if (null !== $member->getLocation()) {
7581
return '';
@@ -84,6 +90,7 @@ public function generateRequestBuilder(StructureShape $shape, bool $needsChecks)
8490
$inputElement = '$v';
8591
} elseif ($member->isRequired()) {
8692
if ($needsChecks) {
93+
$this->usedClassesAdd(InvalidArgument::class);
8794
$body = 'if (null === $v = $this->PROPERTY) {
8895
throw new InvalidArgument(sprintf(\'Missing parameter "NAME" for "%s". The value cannot be null.\', __CLASS__));
8996
}
@@ -112,14 +119,14 @@ public function generateRequestBuilder(StructureShape $shape, bool $needsChecks)
112119
]);
113120
}, $shape->getMembers()));
114121

115-
return ['array', strtr('
122+
return new SerializerResultBuilder('array', strtr('
116123
$payload = [];
117124
CHILDREN_CODE
118125
119126
return $payload;
120127
', [
121128
'CHILDREN_CODE' => $body,
122-
])];
129+
]), $this->usedClassesFlush());
123130
}
124131

125132
protected function dumpArrayBoolean(string $output, string $input, Shape $shape): string
@@ -227,6 +234,7 @@ private function dumpArrayMap(string $output, string $input, string $contextProp
227234
$mapKeyShape = $shape->getKey()->getShape();
228235
if (!empty($mapKeyShape->getEnum())) {
229236
$enumClassName = $this->namespaceRegistry->getEnum($mapKeyShape);
237+
$this->usedClassesAdd(InvalidArgument::class);
230238
$validateEnum = strtr('if (!ENUM_CLASS::exists($name)) {
231239
throw new InvalidArgument(sprintf(\'Invalid key for "%s". The value "%s" is not a valid "ENUM_CLASS".\', __CLASS__, $name));
232240
}', [
@@ -265,6 +273,7 @@ private function dumpArrayScalar(string $output, string $input, string $contextP
265273
];
266274
if (!empty($shape->getEnum())) {
267275
$enumClassName = $this->namespaceRegistry->getEnum($shape);
276+
$this->usedClassesAdd(InvalidArgument::class);
268277
$body = 'if (!ENUM_CLASS::exists(INPUT)) {
269278
throw new InvalidArgument(sprintf(\'Invalid parameter "PROPERTY" for "%s". The value "%s" is not a valid "ENUM_CLASS".\', __CLASS__, INPUT));
270279
}

0 commit comments

Comments
 (0)