Skip to content

Commit c4d5539

Browse files
authored
Generate timestamp parsing that static analysis accepts without an annotation (#2132)
1 parent 2f397ba commit c4d5539

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

‎src/Generator/ResponseParser/JsonRpcParser.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class JsonRpcParser extends RestJsonParser
1616
protected function parseResponseTimestamp(Shape $shape, string $input, bool $required): string
1717
{
1818
if ($required) {
19-
$body = '/** @var \DateTimeImmutable $d */ $d = \DateTimeImmutable::createFromFormat(\'U.u\', \sprintf(\'%.6F\', INPUT))';
19+
$body = $this->rejectUnparsableTimestamp('\DateTimeImmutable::createFromFormat(\'U.u\', \sprintf(\'%.6F\', INPUT))');
2020
} else {
2121
$body = '(isset(INPUT) && ($d = \DateTimeImmutable::createFromFormat(\'U.u\', \sprintf(\'%.6F\', INPUT)))) ? $d : null';
2222
}

‎src/Generator/ResponseParser/RestJsonParser.php‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use AsyncAws\CodeGenerator\Generator\GeneratorHelper;
2020
use AsyncAws\CodeGenerator\Generator\Naming\ClassName;
2121
use AsyncAws\CodeGenerator\Generator\Naming\NamespaceRegistry;
22+
use AsyncAws\Core\Exception\UnparsableResponse;
2223
use Nette\PhpGenerator\Method;
2324
use Nette\PhpGenerator\Visibility;
2425

@@ -161,14 +162,28 @@ protected function parseResponseTimestamp(Shape $shape, string $input, bool $req
161162
}
162163

163164
if ($required) {
164-
$body = '/** @var \DateTimeImmutable $d */ $d = ' . $body;
165+
$body = $this->rejectUnparsableTimestamp($body);
165166
} else {
166167
$body = 'isset(INPUT) && ($d = ' . $body . ') ? $d : null';
167168
}
168169

169170
return strtr($body, ['INPUT' => $input]);
170171
}
171172

173+
/**
174+
* createFromFormat() returns false on a malformed value, and no annotation convinces static
175+
* analysis that it cannot happen here. The failure is raised instead, so that the generated
176+
* code needs no baseline entry: the value comes from the response, which is exactly what
177+
* UnparsableResponse describes.
178+
*/
179+
protected function rejectUnparsableTimestamp(string $body): string
180+
{
181+
$className = ClassName::createFromFqdn(UnparsableResponse::class);
182+
$this->imports[] = $className;
183+
184+
return $body . ' ?: throw new ' . $className->getName() . "('Invalid timestamp received.')";
185+
}
186+
172187
private function getInputAccessorName(Member $member): string
173188
{
174189
if ($member instanceof StructureMember) {

0 commit comments

Comments
 (0)