diff --git a/gatherling/Helpers/Request.php b/gatherling/Helpers/Request.php index 32f1b3533..2d6e3f211 100644 --- a/gatherling/Helpers/Request.php +++ b/gatherling/Helpers/Request.php @@ -18,7 +18,7 @@ public function int(string $key, int|false $default = false): int public function optionalInt(string $key): ?int { - return marshal($this->vars[$key] ?? null)->optionalInt(); + return marshal($this->coalesceNumeric($key))->optionalInt(); } public function string(string $key, string|false $default = false): string @@ -39,7 +39,7 @@ public function float(string $key, float|false $default = false): float /** @psalm-suppress PossiblyUnusedMethod */ public function optionalFloat(string $key): ?float { - return marshal($this->vars[$key] ?? null)->optionalFloat(); + return marshal($this->coalesceNumeric($key))->optionalFloat(); } /** @return list */ @@ -71,4 +71,17 @@ public function dictString(string $key): array { return marshal($this->vars[$key] ?? null)->dictString(); } + + // Coalesce like ?? does, but additionally if the value is an empty string, return null. + // This is how we want to treat something like 'season=' in a querystring. + private function coalesceNumeric(string $key): mixed + { + if (!isset($this->vars[$key])) { + return null; + } + if ($this->vars[$key] === '') { + return null; + } + return $this->vars[$key]; + } } diff --git a/tests/Helpers/MarshallerTest.php b/tests/Helpers/MarshallerTest.php index 8b8ecdc08..1afaf6461 100644 --- a/tests/Helpers/MarshallerTest.php +++ b/tests/Helpers/MarshallerTest.php @@ -36,6 +36,12 @@ public function testOptionalInt(): void marshal(123.45)->optionalInt(); } + public function testOptionalIntThrowsOnEmptyString(): void + { + $this->expectException(MarshalException::class); + marshal('')->optionalInt(); + } + public function testString(): void { $this->assertEquals('hello', marshal('hello')->string('key')); diff --git a/tests/Helpers/RequestTest.php b/tests/Helpers/RequestTest.php index 75d9814b2..c480b410e 100644 --- a/tests/Helpers/RequestTest.php +++ b/tests/Helpers/RequestTest.php @@ -25,6 +25,13 @@ public function testIntMissing(): void $request->int('baz'); } + public function testIntThrowsOnEmptyString(): void + { + $request = new Request(['foo' => '']); + $this->expectException(MarshalException::class); + $request->int('foo'); + } + public function testOptionalInt(): void { $request = new Request(['foo' => '123', 'bar' => '123.4']); @@ -34,6 +41,12 @@ public function testOptionalInt(): void $request->optionalInt('bar'); } + public function testOptionalIntReturnsNullOnEmptyString(): void + { + $request = new Request(['foo' => '']); + $this->assertNull($request->optionalInt('foo')); + } + public function testFloat(): void { $request = new Request(['foo' => '123.45']);