diff --git a/src/Bindings/MySQL/MySQLNumericBindings.php b/src/Bindings/MySQL/MySQLNumericBindings.php index 7f3ece6..36c87ab 100644 --- a/src/Bindings/MySQL/MySQLNumericBindings.php +++ b/src/Bindings/MySQL/MySQLNumericBindings.php @@ -63,7 +63,25 @@ public function bInt(float | bool | int | string | null $value = null, bool $nul throw new InvalidArgumentException('Can not bind "' . $value . '" in integer spot.'); } - return [(int)sprintf('%u', $value), PDO::PARAM_INT]; + // Numeric strings become int or float; floats are truncated toward zero, like (int). + $number = +$value; + + if (is_float($number)) { + // An integer-only string that still became a float overflowed the integer range. + $overflowed = is_string($value) && preg_match('/^\s*[+-]?\d+\s*$/', $value) === 1; + + // (int) on a float outside the integer range gives a meaningless value, so refuse it. + // (float)PHP_INT_MAX rounds up to 2^63, which is already out of range, hence >=. + if ($overflowed || !is_finite($number) || $number >= PHP_INT_MAX || $number < PHP_INT_MIN) { + throw new InvalidArgumentException( + 'Can not bind ' . var_export($value, true) . ' in integer spot: out of range.' + ); + } + + $number = (int)$number; + } + + return [$number, PDO::PARAM_INT]; } /** diff --git a/tests/MySQLNumericBindingsTest.php b/tests/MySQLNumericBindingsTest.php new file mode 100644 index 0000000..16503bb --- /dev/null +++ b/tests/MySQLNumericBindingsTest.php @@ -0,0 +1,68 @@ + + */ + public static function intProvider(): array + { + return [ + 'positive int' => [42, 42], + 'zero' => [0, 0], + 'negative int' => [-5, -5], + 'negative numeric string' => ['-5', -5], + 'numeric string' => ['123', 123], + 'float truncates' => [1.9, 1], + 'negative float truncates toward zero' => [-1.9, -1], + 'float string truncates' => ['2.5', 2], + 'exponent string' => ['1e3', 1000], + 'PHP_INT_MAX' => [PHP_INT_MAX, PHP_INT_MAX], + 'PHP_INT_MIN' => [PHP_INT_MIN, PHP_INT_MIN], + 'PHP_INT_MIN as string' => ['-9223372036854775808', PHP_INT_MIN], + ]; + } + + /** + * @dataProvider intProvider + */ + public function testBIntBindsIntegers(float | int | string $value, int $expected): void + { + $this->assertSame([$expected, PDO::PARAM_INT], (new MySQLNumericBindings())->bInt($value)); + } + + /** + * @return array + */ + public static function outOfRangeProvider(): array + { + return [ + 'string above PHP_INT_MAX' => ['9223372036854775808'], + 'string below PHP_INT_MIN' => ['-9223372036854775809'], + 'huge float' => [1e20], + 'huge negative float' => [-1e20], + 'INF' => [INF], + 'NAN' => [NAN], + ]; + } + + /** + * @dataProvider outOfRangeProvider + */ + public function testBIntRejectsOutOfRange(float | string $value): void + { + $this->expectException(InvalidArgumentException::class); + + (new MySQLNumericBindings())->bInt($value); + } +}