From 444365f99e10eb0270873bc55f73cf897670ecb3 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:30:08 +0200 Subject: [PATCH] Coerce scalar properties without loss Hydrators compile with strict_types; when the constructor rejects an argument, plain int, float, string and bool fields are converted only if lossless and the call is retried, so input of the declared type costs nothing extra. Lossy input throws DataHydrationException naming the field. Closes #24. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 2 + CHANGELOG.md | 6 + UPGRADE-3.0.md | 14 +- docs/features/hydration.md | 20 +++ src/BaseData.php | 2 +- src/Support/ClassMetaFactory.php | 10 ++ src/Support/HydratorCompiler.php | 61 +++++-- src/Support/MetadataRegistry.php | 4 +- src/Support/ParameterMeta.php | 2 + src/Support/ScalarCoercion.php | 84 +++++++++ src/Support/ValueCaster.php | 4 +- tests/Fixtures/ScalarData.php | 30 ++++ tests/Fixtures/ScalarPropertiesData.php | 14 ++ tests/Fixtures/ThrowsTypeErrorData.php | 19 ++ tests/FromResultTest.php | 4 +- tests/ScalarCoercionTest.php | 169 ++++++++++++++++++ tests/StackTraceRedactionTest.php | 11 +- 17 files changed, 428 insertions(+), 28 deletions(-) create mode 100644 src/Support/ScalarCoercion.php create mode 100644 tests/Fixtures/ScalarData.php create mode 100644 tests/Fixtures/ScalarPropertiesData.php create mode 100644 tests/Fixtures/ThrowsTypeErrorData.php create mode 100644 tests/ScalarCoercionTest.php diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md index deb348a..2cc5a05 100644 --- a/.claude/skills/migrate-from-v2-to-v3/SKILL.md +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -92,6 +92,8 @@ the table in `UPGRADE-3.0.md`. Look at where the data comes from: second becomes `false` (it was `true`). - **JSON APIs:** `1.0` into `int` still works; `1.5` throws. - **Database rows / internal arrays:** usually already typed. +- **Union types** (`int|string`, `float|int`): no longer coerced at all; + `true` or `1.5` into `int|string` now throws a `TypeError`. If a property legitimately receives lossy input, **STOP AND ASK** before choosing between retyping it (`float`), adding a cast (`IntegerCast`, diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ab03d9..fe4db74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,12 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. validation error under `'$pipeline'` (class pipe) or the property's key. `#[RejectUnknownKeys]` still checks the raw input; `from()` is unchanged (#23). +- A property typed `int`, `float`, `string` or `bool` without a cast takes + only values that convert without loss (`"3"` and `3.0` into `int`, + `"false"` into `bool` as `false`); anything else throws + `DataHydrationException` naming the field. Union types are checked in + strict mode. In 2.x PHP's weak coercion applied (`"1.9"` became `1`, + `"false"` became `true`) (#24). - A non-null value that matches no case of a nullable enum property throws `DataHydrationException` (`tryFrom()` returns `null`, `fromResult()` reports the field) instead of becoming `null`. `#[Cast(new EnumCast(...))]` diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index cf17f3f..9a3ae61 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -88,14 +88,20 @@ takes only values that convert without loss: |---|---|---| | `int` | int, a float with no fraction, a string of digits with an optional `-` within range | `"1.9"`, `1.9`, `true`, `"abc"` | | `float` | int, float, a numeric string | `true`, `"abc"` | -| `string` | string, int, float | `true`, arrays, objects | +| `string` | string, int, float, `Stringable` | `true`, arrays, other objects | | `bool` | bool, and `"1"`, `"0"`, `"true"`, `"false"`, `"on"`, `"off"`, `"yes"`, `"no"`, `""`, `1`, `0` | `"maybe"`, `2` | -Anything else throws `DataHydrationException` naming the field; `tryFrom()` -returns `null` and `fromResult()` reports it under the field's key. +Anything else throws `DataHydrationException` naming the field ("Invalid +value for field 'age': Cannot convert string to int without loss."); `tryFrom()` +returns `null` and `fromResult()` reports it under the field's key. `with()` +applies the same rules. + +Union types (`int|string`) are not coerced: PHP checks them in strict mode, +so `int|string` given `1.5` or `true` throws a `TypeError`. **Affected:** inputs that relied on lossy coercion: decimals into `int`, -`"false"`/`"no"` strings into `bool` (now `false`, previously `true`). +`"false"`/`"no"` strings into `bool` (now `false`, previously `true`), and +values PHP coerced into a union type. **What to do:** type the property as `float`, add a cast (`IntegerCast`, `BooleanCast`), or fix the input. diff --git a/docs/features/hydration.md b/docs/features/hydration.md index f87686e..24c7987 100644 --- a/docs/features/hydration.md +++ b/docs/features/hydration.md @@ -182,6 +182,26 @@ UserData::from(['name' => 'Alice', 'email' => 'alice@example.com']); // phone = null, age = 0 ``` +## Scalar Types + +A property typed `int`, `float`, `string` or `bool` (nullable or not) without a cast takes a value of another scalar type only when it converts without loss: + +```php +ProductData::from(['quantity' => '3']); // 3 +ProductData::from(['quantity' => 3.0]); // 3 +ProductData::from(['quantity' => '3.5']); // DataHydrationException: +// Invalid value for field 'quantity': Cannot convert string to int without loss. +``` + +| Type | Accepted | Rejected | +|---|---|---| +| `int` | int, a float with no fraction, a string of digits with an optional `-` within range | `"1.9"`, `1.9`, `true`, `"abc"` | +| `float` | int, float, a finite numeric string | `true`, `"abc"` | +| `string` | string, int, float, `Stringable` | `true`, arrays, other objects | +| `bool` | bool, and `"1"`, `"0"`, `"true"`, `"false"`, `"on"`, `"off"`, `"yes"`, `"no"`, `""`, `1`, `0` | `"maybe"`, `2` | + +Values of the declared type pass straight to the constructor; conversion runs only when PHP rejects one. Union types (`int|string`) are checked by PHP in strict mode and not converted. For any other conversion, use a [cast](../attributes/cast.md) such as `IntegerCast` or `BooleanCast`. + ## Missing Required Fields If a required field (non-nullable, no default) is missing, `DataHydrationException` is thrown: diff --git a/src/BaseData.php b/src/BaseData.php index b266a5e..6d30d6a 100644 --- a/src/BaseData.php +++ b/src/BaseData.php @@ -226,7 +226,7 @@ public function with(#[\SensitiveParameter] mixed ...$overrides): static if (array_key_exists($param->phpName, $overrides)) { $value = $overrides[$param->phpName]; $value = match (true) { - $param->isPlain => $value, + $param->isPlain && $param->scalarType === null => $value, $param->isSensitive => ValueCaster::castSensitive($param, $value, static::class), default => ValueCaster::cast($param, $value), }; diff --git a/src/Support/ClassMetaFactory.php b/src/Support/ClassMetaFactory.php index b76cc64..de75ec6 100644 --- a/src/Support/ClassMetaFactory.php +++ b/src/Support/ClassMetaFactory.php @@ -386,9 +386,19 @@ enumClass: $enumClass, phpType: RuleInferrer::phpTypeName($parameter), xmlSource: self::xmlSource($parameter, $phpName, (string) $inputNames[0]), isSensitive: $parameter->getAttributes(Sensitive::class) !== [], + scalarType: self::scalarType($parameter), ); } + private static function scalarType(ReflectionParameter|ReflectionProperty $parameter): ?string + { + $type = $parameter->getType(); + + return $type instanceof \ReflectionNamedType && in_array($type->getName(), ['int', 'float', 'string', 'bool'], true) + ? $type->getName() + : null; + } + private static function bindCaster(CastsValue $caster, ReflectionParameter|ReflectionProperty $parameter): CastsValue { return $caster instanceof BindsToField diff --git a/src/Support/HydratorCompiler.php b/src/Support/HydratorCompiler.php index 8e4a83e..85407ee 100644 --- a/src/Support/HydratorCompiler.php +++ b/src/Support/HydratorCompiler.php @@ -96,7 +96,7 @@ public static function compile(string $class): Closure $p = $meta->parameters; $pipes = $meta->pipes; - $fn = eval('return '.self::generate($class, $meta).';'); + $fn = eval('declare(strict_types=1); return '.self::generate($class, $meta).';'); // Any direct property assignment (constructor-less, or a hybrid // class's extra properties) may target a readonly property, which @@ -172,7 +172,7 @@ public static function compilePipeless(string $class): Closure $p = $meta->parameters; $pipes = $meta->pipes; - $fn = eval('return '.self::generate($class, $meta).';'); + $fn = eval('declare(strict_types=1); return '.self::generate($class, $meta).';'); return self::$pipelessHydrators[$class] = self::bindForAssignments($fn, $meta, $class); } @@ -243,28 +243,41 @@ static function (#[\\SensitiveParameter] array \$d) use (\$p, \$pipes): \\{$clas } $unknownCheck = self::buildUnknownKeysCheck($class, $meta); - [$body, $argList] = self::buildParts($class, $meta); - $scrub = " } catch (\\Throwable \$e) {\n" - ." throw \\StdOut\\SimpleDataObjects\\Support\\Redactor::scrubConstructorArguments(\$e, \\{$class}::class);\n" + [$body, $argList] = self::buildParts($class, $meta, coerceInline: false); + $construct = "new \\{$class}({$argList})"; + $rethrow = "throw \\StdOut\\SimpleDataObjects\\Support\\Redactor::scrubConstructorArguments(\$e, \\{$class}::class);"; + $catch = static fn (string $retry): string => " } catch (\\Throwable \$e) {\n" + ." if (! \$e instanceof \\TypeError || (\$c = \\StdOut\\SimpleDataObjects\\Support\\ScalarCoercion::input(\$d, \$p)) === null) {\n" + ." {$rethrow}\n" + ." }\n" + ." \$d = \$c;\n" + ." try {\n" + ." {$retry}\n" + ." } catch (\\Throwable \$e) {\n" + ." {$rethrow}\n" + ." }\n" ." }\n"; if ($meta->hasExtraProperties) { $extraBody = self::buildPropertyAssignments($class, $meta, includePipesPrelude: false); + $retry = $catch("\$o = {$construct};"); return <<inputNames) === 1 && $param->isPlain && $param->allowsNull && ! $param->isOptional && (! $param->hasDefault || $param->defaultValue === null)) { - $args[] = "\$d[{$f['key']}] ?? null"; + $args[] = $coerceInline ? self::plainRead($i, $param, "\$d[{$f['key']}] ?? null") : "\$d[{$f['key']}] ?? null"; continue; } @@ -398,17 +411,37 @@ private static function resolveKeyExpr(int $i, array $names, string &$body): arr return [$var, "{$var} !== null"]; } + private static function plainRead(int $i, ParameterMeta $param, string $read): string + { + if ($param->scalarType === null) { + return $read; + } + + $v = "\$s{$i}"; + $check = match ($param->scalarType) { + 'int' => "\\is_int({$v} = {$read})", + 'float' => "\\is_float({$v} = {$read}) || \\is_int({$v})", + 'string' => "\\is_string({$v} = {$read})", + default => "\\is_bool({$v} = {$read})", + }; + $nullable = $param->allowsNull ? " || {$v} === null" : ''; + $field = var_export((string) $param->inputNames[0], true); + + return "({$check}{$nullable} ? {$v} : \\StdOut\\SimpleDataObjects\\Support\\ScalarCoercion::coerce({$v}, '{$param->scalarType}', {$field}))"; + } + /** * Shared per-parameter pieces: the hot path inlines them into a ternary, * the collecting path wraps them in try/catch. * * @return array{key: string, presence: string, present: string, absent: string, missingKey: string} */ - private static function fieldAccessExpr(int $i, ParameterMeta $param, string $classExport, string &$body): array + private static function fieldAccessExpr(int $i, ParameterMeta $param, string $classExport, string &$body, bool $coerceInline = true): array { [$key, $presence] = self::resolveKeyExpr($i, $param->inputNames, $body); $present = match (true) { + $param->isPlain && $coerceInline => self::plainRead($i, $param, "\$d[{$key}]"), $param->isPlain => "\$d[{$key}]", $param->isSensitive => "\\StdOut\\SimpleDataObjects\\Support\\ValueCaster::castSensitive(\$p[{$i}], \$d[{$key}], {$classExport})", default => "\\StdOut\\SimpleDataObjects\\Support\\ValueCaster::cast(\$p[{$i}], \$d[{$key}])", @@ -468,7 +501,7 @@ private static function buildPropertyAssignments(string $class, ClassMeta $meta, // Missing key and explicit null both resolve to null — ?? is exact here. // Only safe for a single accepted name; see resolveKeyExpr(). if (count($param->inputNames) === 1 && $param->isPlain && $param->allowsNull && ! $param->isOptional && (! $param->hasDefault || $param->defaultValue === null)) { - $body .= " {$target} = \$d[{$f['key']}] ?? null;\n"; + $body .= " {$target} = ".self::plainRead($i, $param, "\$d[{$f['key']}] ?? null").";\n"; continue; } diff --git a/src/Support/MetadataRegistry.php b/src/Support/MetadataRegistry.php index 5b73c17..f089a7b 100644 --- a/src/Support/MetadataRegistry.php +++ b/src/Support/MetadataRegistry.php @@ -12,7 +12,7 @@ final class MetadataRegistry */ private const string FILE_SUFFIX = '.meta.php'; - private const string FORMAT = 'sdo-cache-4'; + private const string FORMAT = 'sdo-cache-5'; /** @var array */ private static array $cache = []; @@ -140,7 +140,7 @@ private static function persist(string $class, string $file, ClassMeta $meta): b $hydrator = HydratorCompiler::generate($class, $meta); $serializer = SerializerCompiler::generate($class, $meta); - $code = "parameters;\n" ."\$pipes = \$meta->pipes;\n\n" diff --git a/src/Support/ParameterMeta.php b/src/Support/ParameterMeta.php index d4d93e1..90f4fd9 100644 --- a/src/Support/ParameterMeta.php +++ b/src/Support/ParameterMeta.php @@ -50,6 +50,7 @@ public function __construct( /** `@name` for an attribute, `#text` for the element's text, otherwise a child element name. */ public readonly ?string $xmlSource = null, public readonly bool $isSensitive = false, + public readonly ?string $scalarType = null, ) { $this->isPlain = $caster === null && $nestedDataClass === null @@ -89,6 +90,7 @@ enumClass: $state['enumClass'], phpType: $state['phpType'] ?? null, xmlSource: $state['xmlSource'] ?? null, isSensitive: $state['isSensitive'] ?? false, + scalarType: $state['scalarType'] ?? null, ); } } diff --git a/src/Support/ScalarCoercion.php b/src/Support/ScalarCoercion.php new file mode 100644 index 0000000..cee4dd2 --- /dev/null +++ b/src/Support/ScalarCoercion.php @@ -0,0 +1,84 @@ + $d + * @param array $parameters + * @return array|null + */ + public static function input(#[\SensitiveParameter] array $d, array $parameters): ?array + { + $coerced = null; + + foreach ($parameters as $param) { + if ($param->scalarType === null || ! $param->isPlain) { + continue; + } + + foreach ($param->inputNames as $name) { + if (! array_key_exists($name, $d) || self::fits($d[$name], $param)) { + continue; + } + + $coerced ??= $d; + $coerced[$name] = self::coerce($d[$name], $param->scalarType, (string) $param->inputNames[0]); + } + } + + return $coerced; + } + + public static function coerce(#[\SensitiveParameter] mixed $value, string $type, string $field): int|float|string|bool + { + $coerced = match ($type) { + 'int' => self::toInt($value), + 'float' => self::toFloat($value), + 'string' => is_string($value) || is_int($value) || is_float($value) || $value instanceof \Stringable ? (string) $value : null, + default => is_bool($value) ? $value : (is_string($value) || is_int($value) ? filter_var($value, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) : null), + }; + + return $coerced ?? throw DataHydrationException::invalidValue( + $field, + new InvalidArgumentException('Cannot convert '.get_debug_type($value)." to {$type} without loss."), + ); + } + + private static function fits(#[\SensitiveParameter] mixed $value, ParameterMeta $param): bool + { + return ($value === null && $param->allowsNull) || match ($param->scalarType) { + 'int' => is_int($value), + 'float' => is_float($value) || is_int($value), + 'string' => is_string($value), + default => is_bool($value), + }; + } + + private static function toInt(#[\SensitiveParameter] mixed $value): ?int + { + return match (true) { + is_int($value) => $value, + is_float($value) => $value >= -self::INT_LIMIT && $value < self::INT_LIMIT && $value === (float) (int) $value ? (int) $value : null, + is_string($value) => filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE), + default => null, + }; + } + + private static function toFloat(#[\SensitiveParameter] mixed $value): int|float|null + { + return match (true) { + is_int($value), is_float($value) => $value, + is_string($value) && is_numeric($value) && is_finite((float) $value) => (float) $value, + default => null, + }; + } +} diff --git a/src/Support/ValueCaster.php b/src/Support/ValueCaster.php index 2581e7a..a05837e 100644 --- a/src/Support/ValueCaster.php +++ b/src/Support/ValueCaster.php @@ -40,7 +40,9 @@ public static function cast(ParameterMeta $meta, #[\SensitiveParameter] mixed $v return self::castEnum($meta, $value); } - return $value; + return $meta->scalarType === null || ($value === null && $meta->allowsNull) + ? $value + : ScalarCoercion::coerce($value, $meta->scalarType, (string) $meta->inputNames[0]); } catch (DataHydrationException $e) { throw $e; } catch (\Throwable $e) { diff --git a/tests/Fixtures/ScalarData.php b/tests/Fixtures/ScalarData.php new file mode 100644 index 0000000..f22fb58 --- /dev/null +++ b/tests/Fixtures/ScalarData.php @@ -0,0 +1,30 @@ + '4111111111111111', 'amount' => 'ten']); $this->assertSame( - ['$construct' => ChargeData::class.'::__construct(): Argument #2 ($amount) must be of type int, string given'], + ['amount' => "Invalid value for field 'amount': Cannot convert string to int without loss."], $result->errors(), ); } diff --git a/tests/ScalarCoercionTest.php b/tests/ScalarCoercionTest.php new file mode 100644 index 0000000..1999983 --- /dev/null +++ b/tests/ScalarCoercionTest.php @@ -0,0 +1,169 @@ + */ + public static function losslessValues(): iterable + { + yield 'int from int' => ['int', 5, 5]; + yield 'int from whole float' => ['int', 5.0, 5]; + yield 'int from digit string' => ['int', '-42', -42]; + yield 'int from the smallest int as float' => ['int', -9.2233720368547758E18, PHP_INT_MIN]; + yield 'float from float' => ['float', 1.5, 1.5]; + yield 'float from int' => ['float', 2, 2.0]; + yield 'float from numeric string' => ['float', '1.25', 1.25]; + yield 'string from string' => ['string', 'abc', 'abc']; + yield 'string from int' => ['string', 7, '7']; + yield 'string from float' => ['string', 1.5, '1.5']; + yield 'string from stringable' => ['string', new class implements \Stringable + { + public function __toString(): string + { + return 'text'; + } + }, 'text']; + yield 'bool from bool' => ['bool', true, true]; + yield 'bool from "false"' => ['bool', 'false', false]; + yield 'bool from "no"' => ['bool', 'no', false]; + yield 'bool from "on"' => ['bool', 'on', true]; + yield 'bool from empty string' => ['bool', '', false]; + yield 'bool from 1' => ['bool', 1, true]; + yield 'bool from 0' => ['bool', 0, false]; + } + + #[DataProvider('losslessValues')] + public function test_lossless_values_are_accepted(string $field, mixed $input, mixed $expected): void + { + $this->assertSame($expected, ScalarData::from([$field => $input])->{$field}); + $this->assertSame($expected, ScalarData::fromResult([$field => $input])->value()->{$field}); + $this->assertSame($expected, ScalarData::from([])->with(...[$field => $input])->{$field}); + } + + /** @return iterable */ + public static function lossyValues(): iterable + { + yield 'int from decimal string' => ['int', '1.9', 'string']; + yield 'int from fractional float' => ['int', 1.9, 'float']; + yield 'int from huge float' => ['int', 1e19, 'float']; + yield 'int from very negative float' => ['int', -1e19, 'float']; + yield 'int from 2 ** 63 as float' => ['int', 9.2233720368547758E18, 'float']; + yield 'int from bool' => ['int', true, 'bool']; + yield 'int from text' => ['int', 'abc', 'string']; + yield 'int from overflowing string' => ['int', '99999999999999999999', 'string']; + yield 'int from null' => ['int', null, 'null']; + yield 'float from bool' => ['float', true, 'bool']; + yield 'float from text' => ['float', 'abc', 'string']; + yield 'float from overflowing string' => ['float', '1e400', 'string']; + yield 'string from bool' => ['string', true, 'bool']; + yield 'string from array' => ['string', ['x'], 'array']; + yield 'bool from "maybe"' => ['bool', 'maybe', 'string']; + yield 'bool from 2' => ['bool', 2, 'int']; + yield 'bool from float' => ['bool', 1.0, 'float']; + } + + #[DataProvider('lossyValues')] + public function test_lossy_values_throw_a_hydration_exception_naming_the_field(string $field, mixed $input, string $given): void + { + $message = "Invalid value for field '{$field}': Cannot convert {$given} to {$field} without loss."; + + $this->assertSame([$field => $message], ScalarData::fromResult([$field => $input])->errors()); + $this->assertNull(ScalarData::tryFrom([$field => $input])); + + try { + ScalarData::from([])->with(...[$field => $input]); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertSame($message, $e->getMessage()); + } + + $this->expectException(DataHydrationException::class); + $this->expectExceptionMessage($message); + + ScalarData::from([$field => $input]); + } + + public function test_nullable_scalars_keep_null_and_coerce_other_values(): void + { + $data = ScalarData::from(['nullableInt' => null, 'is_flag' => 'yes', 'piped' => ' 7 ']); + + $this->assertNull($data->nullableInt); + $this->assertTrue($data->flag); + $this->assertSame(7, $data->piped); + $this->assertNull(ScalarData::from(['piped' => null])->piped); + $this->assertSame(3, ScalarData::from(['nullableInt' => '3'])->nullableInt); + $this->assertNull(ScalarData::from([])->with(nullableInt: null)->nullableInt); + $this->assertSame(['piped'], array_keys(ScalarData::fromResult(['piped' => ' 1.5 '])->errors())); + } + + public function test_union_types_are_left_to_php(): void + { + $this->assertSame('abc', ScalarData::from(['union' => 'abc'])->union); + $this->assertNull(MetadataRegistry::get(ScalarData::class)->parameters[8]->scalarType); + } + + public function test_typed_properties_are_coerced_the_same_way(): void + { + $data = ScalarPropertiesData::from(['count' => '12', 'ratio' => '0.5']); + + $this->assertSame([12, 0.5], [$data->count, $data->ratio]); + $this->assertNull(ScalarPropertiesData::from(['count' => 1])->ratio); + $this->assertSame(['count'], array_keys(ScalarPropertiesData::fromResult(['count' => '1.5'])->errors())); + + $this->expectException(DataHydrationException::class); + + ScalarPropertiesData::from(['count' => 1, 'ratio' => 'abc']); + } + + public function test_hybrid_classes_coerce_constructor_arguments_and_keep_extra_properties(): void + { + $data = HybridChargeData::from(['pan' => 4111, 'amount' => '5', 'reference' => 'r']); + + $this->assertSame(['4111', 5, 'r'], [$data->pan, $data->amount, $data->reference]); + } + + public function test_cast_properties_are_left_to_their_cast(): void + { + $this->assertSame([1, 5], [ScalarData::from(['casted' => '1.9', 'int' => '5'])->casted, ScalarData::from(['int' => '5'])->int]); + } + + /** @return iterable}> */ + public static function typeErrorInputs(): iterable + { + yield 'already fitting' => [['count' => 5, 'ratio' => 1]]; + yield 'coerced first' => [['count' => '5']]; + } + + /** @param array $input */ + #[DataProvider('typeErrorInputs')] + public function test_a_type_error_from_the_constructor_body_is_rethrown_without_running_it_twice(array $input): void + { + ThrowsTypeErrorData::$calls = 0; + + try { + ThrowsTypeErrorData::from($input); + $this->fail('Expected a TypeError.'); + } catch (\TypeError $e) { + $this->assertSame('Count rejected.', $e->getMessage()); + } + + $this->assertSame(1, ThrowsTypeErrorData::$calls); + } +} diff --git a/tests/StackTraceRedactionTest.php b/tests/StackTraceRedactionTest.php index b239113..761be18 100644 --- a/tests/StackTraceRedactionTest.php +++ b/tests/StackTraceRedactionTest.php @@ -12,6 +12,7 @@ use StdOut\SimpleDataObjects\Casts\DateTimeImmutableCast; use StdOut\SimpleDataObjects\Casts\EncryptedCast; use StdOut\SimpleDataObjects\Casts\UuidCast; +use StdOut\SimpleDataObjects\Exceptions\DataHydrationException; use StdOut\SimpleDataObjects\Laravel\DataCollectionCast; use StdOut\SimpleDataObjects\Laravel\DataObjectCast; use StdOut\SimpleDataObjects\Tests\Fixtures\CastableAddressData; @@ -22,6 +23,7 @@ use StdOut\SimpleDataObjects\Tests\Fixtures\OrderWithUuidData; use StdOut\SimpleDataObjects\Tests\Fixtures\SensitiveCardData; use StdOut\SimpleDataObjects\Tests\Fixtures\ThrowingPipeData; +use StdOut\SimpleDataObjects\Tests\Fixtures\ThrowsTypeErrorData; use StdOut\SimpleDataObjects\Tests\Fixtures\ValidatedUserData; use StdOut\SimpleDataObjects\Tests\Fixtures\WireableEventData; use Throwable; @@ -65,7 +67,8 @@ public static function failingCalls(): iterable yield 'encrypted cast' => [static fn () => (new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='))->get($pan.'!')]; yield 'data pipe' => [static fn () => ThrowingPipeData::from(['name' => $pan])]; yield 'fromLivewire' => [static fn () => WireableEventData::fromLivewire(['name' => $pan])]; - yield 'constructor type error' => [static fn () => ChargeData::from(['pan' => $pan, 'amount' => 'ten'])]; + yield 'lossy scalar' => [static fn () => ChargeData::from(['pan' => $pan, 'amount' => 'ten'])]; + yield 'type error after coercion' => [static fn () => ThrowsTypeErrorData::from(['count' => $pan])]; yield 'constructor throws' => [static fn () => ChargeData::from(['pan' => $pan, 'amount' => -1, 'cvv' => '123'])]; yield 'inherited constructor, extra properties' => [static fn () => HybridChargeData::from(['pan' => $pan, 'amount' => -1])]; yield 'constructor throws in fromLazy' => [static fn () => ChargeData::fromLazy(['pan' => $pan, 'amount' => -1])->amount]; @@ -104,10 +107,10 @@ public function test_constructor_exception_keeps_type_message_line_and_previous( } } - public function test_constructor_type_error_stays_a_type_error(): void + public function test_lossy_scalar_is_a_hydration_exception_naming_the_field(): void { - $this->expectException(\TypeError::class); - $this->expectExceptionMessage('Argument #2 ($amount) must be of type int'); + $this->expectException(DataHydrationException::class); + $this->expectExceptionMessage("Invalid value for field 'amount': Cannot convert string to int without loss."); ChargeData::from(['pan' => self::PAN, 'amount' => 'ten']); }