From b9291782b0272aede054dac1037b5f3e0bc41324 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 12:40:24 +0200 Subject: [PATCH 01/10] Prepare the 3.x branch for 3.0 CI runs on pushes and pull requests to 3.x, and a dev-3.x branch alias lets applications try it as 3.0.x-dev. UPGRADE-3.0.md describes each planned behaviour change, who is affected and what to do; the migrate-from-v2-to-v3 skill walks a codebase through it. Both are updated in the pull request that implements each change (milestone 3.0.0). CONTRIBUTING.md documents which branch takes which kind of change. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 146 ++++++++++++++++++ .github/workflows/security.yml | 4 +- .github/workflows/tests.yml | 4 +- CONTRIBUTING.md | 9 ++ UPGRADE-3.0.md | 146 ++++++++++++++++++ composer.json | 5 + 6 files changed, 310 insertions(+), 4 deletions(-) create mode 100644 .claude/skills/migrate-from-v2-to-v3/SKILL.md create mode 100644 UPGRADE-3.0.md diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md new file mode 100644 index 0000000..7bb2b2e --- /dev/null +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -0,0 +1,146 @@ +--- +name: migrate-from-v2-to-v3 +description: Upgrade a PHP/Laravel codebase from std-out/simple-data-objects 2.x to 3.0 — inventories every data class affected by the 3.0 behaviour changes (nested #[Rules] without #[InferRules], pipes before validation, lossless scalar coercion, invalid enums on nullable properties, cast exceptions, FloatCast finite default, weak legacy EncryptedCast keys), adapts each one, flags data-dependent decisions for human review, and verifies with the test suite. Use when the user asks to upgrade, migrate or move simple-data-objects (or "SDO") from version 2 to version 3. +--- + +# Upgrade Simple Data Objects from 2.x to 3.0 + +3.0 removes no public API. Every change makes the library reject input that +2.x accepted or silently changed, so the risk is in **data**, not in code +that fails to compile. Work change by change, run the tests after each one, +and stop to ask the human at every **STOP AND ASK** instead of guessing: +whether input that 3.0 rejects is a bug or a real client is the owner's call. + +The authoritative description of every change is `UPGRADE-3.0.md` in the +package (`vendor/std-out/simple-data-objects/UPGRADE-3.0.md`). Read it first. + +## Before starting + +1. Read `composer.json` and `composer.lock`. If the installed version is + below 2.9, upgrade to the latest 2.x first and get the tests green there + — 2.9 adds the deprecation notices this skill relies on. +2. Run the test suite on 2.x and record the result. If it is not green, + **STOP AND ASK** — pre-existing failures must not be blamed on the upgrade. +3. Collect 2.9 deprecations: in Laravel read the `deprecations` log channel + (`storage/logs`, or the channel configured in `config/logging.php`); in + PHPUnit set `` and rerun. + Note every `simple-data-objects 2.9` message. +4. **Encryption keys first.** If any `EncryptedCast` logged the weak-key + deprecation, do Step 7 on 2.x and deploy it **before** changing the + version constraint. Upgrading first locks the application out of data + encrypted with that key. +5. Change the constraint (`"std-out/simple-data-objects": "^3.0"`), run + `composer update std-out/simple-data-objects`, then clear the metadata + cache: `php artisan sdo:clear` (Laravel) or + `MetadataRegistry::clearCache()`. + +## Step 1 — inventory + +``` +grep -rln "StdOut\\\\SimpleDataObjects" --include=*.php app src lib 2>/dev/null +``` + +For every data class (`extends BaseData`) record: nested data-class or +`#[DataCollection]` properties, `#[Rules]` / `#[InferRules]`, `#[Pipe]`, +scalar-typed properties without `#[Cast]`, enum properties, `#[Cast]` usages, +`EncryptedCast`. Record every call site of `fromValidated(`, `validate(`, +`fromValidatedResult(`, `fromRequest(` and controller injection of data +classes. Steps 2 and 3 only matter for classes reached through those calls. + +## Step 2 — nested `#[Rules]` without `#[InferRules]` + +Find parents **without** `#[InferRules]` that have a property typed as a data +class (or `#[DataCollection(X::class)]`) where that class, or anything it +nests, has `#[Rules]`. In 3.0 those nested rules apply. + +For each one, write a test that posts the real payload shape through the +validating call site. If it now fails, **STOP AND ASK**: is the nested rule +correct (the payload is the bug) or was it never meant for this endpoint +(remove or move the rule)? Do not loosen rules on your own. + +## Step 3 — pipes run before validation + +Find classes with both `#[Pipe]` (class or property) and rules. For each pipe: + +- **Rules must describe the piped value.** If the pipe changes the type or + shape (string → array, string → int, nesting), update the rules for that + field. If it only normalises (trim, lowercase), the rules usually stay but + can now be tighter. +- **The pipe now sees unvalidated input.** Read its `handle()`; if it assumes + a type (calls `trim()`, `explode()`, indexes an array), make it pass other + types through unchanged (`is_string($value) ? trim($value) : $value`). + A pipe that throws becomes a validation error under `'$pipeline'`. + +Add a test with input that only passes after the pipe (e.g. `' abc '` for +`min:3` + trim) and one that the pipe cannot handle (e.g. an array). + +## Step 4 — scalar coercion + +Find scalar-typed constructor properties (`int`, `float`, `string`, `bool`, +nullable or not) **without** `#[Cast]`. 3.0 accepts only lossless input — see +the table in `UPGRADE-3.0.md`. Look at where the data comes from: + +- **Forms / query strings:** digits into `int` still work. Decimals into + `int` and `"false"`/`"no"` into `bool` change: the first now throws, the + second becomes `false` (it was `true`). +- **JSON APIs:** `1.0` into `int` still works; `1.5` throws. +- **Database rows / internal arrays:** usually already typed. + +If a property legitimately receives lossy input, **STOP AND ASK** before +choosing between retyping it (`float`), adding a cast (`IntegerCast`, +`BooleanCast`) or rejecting the input. Never add a cast just to make a test +pass without asking. + +## Step 5 — enums on nullable properties + +Find nullable enum properties (`?Status`, `Status|null`). An unknown value +now throws instead of becoming `null`. If clients send unknown values on +purpose (e.g. forward compatibility), **STOP AND ASK** — the options are a +rule (`Rule::enum`) that rejects them with a message, or a pipe that maps +them to `null` explicitly. + +## Step 6 — exceptions from hydration + +Search for code catching the old exception types around hydration: + +``` +grep -rnE "catch \((\\\\)?(TypeError|Error|InvalidArgumentException|ValueError|Throwable)" --include=*.php app src +``` + +Where the `try` block calls `from(`, `fromJson(`, `collection(`, `with(` or +`fromModel(`, catch `StdOut\SimpleDataObjects\Exceptions\DataHydrationException` +instead (cast failures now arrive as that type, with the original as +`getPrevious()`), or switch to `tryFrom()` / `fromResult()`. Leave unrelated +catches alone. + +`FloatCast`: find `new FloatCast` without `finite:`. 3.0 rejects `INF`/`NAN`. +Only if a field must store them, add `finite: false` — **STOP AND ASK** first. + +## Step 7 — weak legacy `EncryptedCast` keys (do this on 2.x) + +Find every `EncryptedCast` built with `key:`, `env:` or `provider:` and no +`keyring:`, and check the key it resolves to. It is strong only if it is 32 +random bytes, raw or base64/base64url. Never print or log the key value; +check length and decodability only. + +For each weak key: + +1. Create an `EncryptionKeyring` implementation with a new key + (`base64_encode(random_bytes(32))`) stored like the application's other + secrets. **STOP AND ASK** where the human wants it stored (env, vault, + KMS); do not invent a location. +2. Change the cast to `new EncryptedCast(env: 'OLD_KEY', keyring: AppKeyring::class)` + so old values stay readable and new ones use the keyring. +3. Deploy on 2.x. Re-encrypt over time where `needsReencryption()` is true + (a queued job or a migration over the table). **STOP AND ASK** before + writing anything that rewrites stored data in bulk. + +In 3.0 the old weak key keeps working only next to `keyring:`. + +## Step 8 — verify + +1. Run the full test suite. Every new failure must map to one of Steps 2–7; + if one does not, **STOP AND ASK** — it is not an expected 3.0 change. +2. Run static analysis if the project has it. +3. Report to the human: classes changed per step, decisions taken at each + STOP AND ASK, and any endpoint whose accepted input got stricter. diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 9a7ad46..0c8a72a 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -2,9 +2,9 @@ name: Security on: push: - branches: [main, v2] + branches: [main, v2, 3.x] pull_request: - branches: [main, v2] + branches: [main, v2, 3.x] schedule: - cron: "0 8 * * *" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 177df1a..4ece5bd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -2,9 +2,9 @@ name: Tests on: push: - branches: [main, v2] + branches: [main, v2, 3.x] pull_request: - branches: [main, v2] + branches: [main, v2, 3.x] permissions: contents: read diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef6fe35..ae07415 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -86,6 +86,15 @@ Found a vulnerability? **Please don't open a public issue.** Email [yuriyzee@gmail.com](mailto:yuriyzee@gmail.com) and we'll coordinate a fix and disclosure. +## Branches + +- `main` — the current release line (2.x until 3.0.0 is out). Fixes and + backward-compatible features go here. +- `3.x` — 3.0 in progress. Changes that alter existing behaviour go here + (milestone [3.0.0](https://github.com/std-out/simple-data-objects/milestone/1)); + update `UPGRADE-3.0.md` in the same pull request. +- `v2`, `v1` — maintenance of older major versions. + ## Pull request checklist - [ ] One logical change per PR — small PRs get reviewed fast. diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md new file mode 100644 index 0000000..e31b5c7 --- /dev/null +++ b/UPGRADE-3.0.md @@ -0,0 +1,146 @@ +# Upgrading from 2.x to 3.0 + +> **Work in progress.** 3.0 is being built on the `3.x` branch, one pull +> request per change (milestone [3.0.0](https://github.com/std-out/simple-data-objects/milestone/1)). +> This guide is updated in the same pull request as each change and is final +> only when 3.0.0 is tagged. To try it: `composer require std-out/simple-data-objects:3.0.x-dev`. + +3.0 changes how input is validated and coerced. Every change makes the +library reject input that 2.x accepted silently or turned into something +else. No public API is removed. Most applications need no code changes, +only a check of the classes each section names. + +The repository ships a [`migrate-from-v2-to-v3` skill](.claude/skills/migrate-from-v2-to-v3/SKILL.md) +for Claude Code that walks a codebase through this guide class by class. + +## Before you upgrade + +1. Update to the latest 2.x (2.9 or later) and run the test suite. +2. Check the `deprecations` log channel (Laravel) or run your tests with + suppressed deprecations reported (PHPUnit + ``). Every 2.9 deprecation + is an error in 3.0. +3. Run your tests with a JSON/form payload for every endpoint that uses + `fromValidated()`, `validate()` or `fromRequest()`. Those are the calls + whose behaviour changes most. + +## Nested `#[Rules]` apply without `#[InferRules]` + +**2.x:** `#[Rules]` on a nested data class, or on the item class of a +`#[DataCollection]`, were checked only when the parent class had +`#[InferRules]`. Without it they were ignored. + +**3.0:** a nested class's rules always apply when the nested value is +present, whether or not the parent has `#[InferRules]`. + +**Affected:** a class with a property typed as another data class (or a +`#[DataCollection]`) whose class has `#[Rules]`, validated through +`fromValidated()`, `validate()`, `fromValidatedResult()` or `fromRequest()`, +where the parent has no `#[InferRules]`. + +**What to do:** nothing, if the nested rules are correct. Input that broke +them now fails validation instead of passing. If a nested rule was never +meant to apply in that context, remove it or move it to the parent. + +## Pipes run before validation + +**2.x:** `fromValidated()` validated the raw input, then `from()` ran the +pipes. `' ab '` passed `min:3` and was trimmed to `'ab'` afterwards. + +**3.0:** `fromValidated()`, `validate()` and `fromValidatedResult()` run the +class and property pipes first, validate the piped values, and hydrate from +them without running the pipes again. `from()` is unchanged. + +**Affected:** any class with both `#[Pipe]` and `#[Rules]` (or +`#[InferRules]`). + +**What to do:** + +- Write rules for the value a pipe produces, not the raw input. A pipe that + turns `"1,2"` into `[1, 2]` now needs an `array` rule, not a `string` rule. +- A pipe now sees invalid input before any rule rejects it. Make it return + unexpected types unchanged instead of failing on them. A pipe that still + throws is reported as a validation error under `'$pipeline'`. + +## Scalar properties are coerced without loss + +**2.x:** generated code ran without `strict_types`, so PHP's own coercion +applied: `int` took `"1.9"` and `1.9` as `1`, and `true` as `1`; `bool` took +`"false"` as `true`; `int` given `"abc"` threw a `TypeError` that named a +library file. + +**3.0:** a property typed `int`, `float`, `string` or `bool` without a cast +takes only values that convert 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 numeric string | `true`, `"abc"` | +| `string` | string, int, float | `true`, arrays, 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. + +**Affected:** inputs that relied on lossy coercion: decimals into `int`, +`"false"`/`"no"` strings into `bool` (now `false`, previously `true`). + +**What to do:** type the property as `float`, add a cast (`IntegerCast`, +`BooleanCast`), or fix the input. + +## Invalid enum values on nullable properties throw + +**2.x:** a value that matched no case became `null` on a `?Status` +property; a non-nullable property already threw. + +**3.0:** a non-null value that matches no case always throws +`DataHydrationException`. `null` stays `null`. + +**What to do:** send `null` (or omit the key with a default) instead of an +unknown value, or validate the value with a rule first. + +## Casts throw `DataHydrationException` + +**2.x:** given a value of the wrong type, several casts raised PHP errors or +warnings: `UuidCast` given an array emitted "Array to string conversion" +before its own exception; `TrimCast`, `BooleanCast`, `DateTimeCast`, +`CommaSeparatedCast`, `MoneyCast` and `#[DataCollection]` raised `Error` or +`TypeError`. + +**3.0:** a cast that cannot handle its input throws +`DataHydrationException` naming the field, with the cast's own exception as +`getPrevious()`. No warnings are emitted. + +**What to do:** catch `DataHydrationException` (or use `tryFrom()` / +`fromResult()`) where you caught `TypeError`, `Error` or +`InvalidArgumentException` around hydration. Custom casts are wrapped the +same way; nothing to change in them. + +## `FloatCast` rejects `INF` and `NAN` by default + +**2.x:** `new FloatCast` accepted `INF` and `NAN` (for example from a JSON +`1e400`); rejecting them was opt-in with `finite: true`. + +**3.0:** `finite` defaults to `true`. Pass `finite: false` to keep accepting +them. + +## Weak legacy `EncryptedCast` keys are rejected + +**2.x:** a key given through `$key`, `$env` or `$provider` (the format +without `keyring:`) could be any string. 2.9 emits `E_USER_DEPRECATED` for a +key that is not 32 random bytes. + +**3.0:** such a key throws `InvalidArgumentException` when it is the only +key source. It is still accepted next to `keyring:`, for reading values +encrypted with it; new values are always written with the keyring. + +**What to do,** for each `EncryptedCast` that logged the 2.9 deprecation: + +1. Add a keyring with a strong current key (`base64_encode(random_bytes(32))`), + keep the old key as `$env`/`$key` next to it, and deploy on 2.x. +2. Re-encrypt stored values over time: `needsReencryption()` tells which + ones still use the old format. +3. Upgrade to 3.0. Once nothing needs re-encryption, drop the old key. + +A key that is already 32 random bytes (raw or base64) keeps working as +before. diff --git a/composer.json b/composer.json index d8228aa..5c38617 100644 --- a/composer.json +++ b/composer.json @@ -64,6 +64,11 @@ "test:coverage": "vendor/bin/phpunit --coverage-text --coverage-clover=build/coverage.xml", "coverage:check": "php bin/check-coverage.php build/coverage.xml 100" }, + "extra": { + "branch-alias": { + "dev-3.x": "3.0.x-dev" + } + }, "minimum-stability": "stable", "prefer-stable": true } From e3c825d71476a641cac96d89fa7d6018e452a6fd Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 12:48:19 +0200 Subject: [PATCH 02/10] Keep the host vendor directory out of the Docker image COPY . . copied the host's vendor/ over the dependencies composer install had just put into the image, so local test runs used whatever the host had installed instead of composer.lock: Laravel 13.23 locally while CI ran 13.44, which hid a failure until CI. node_modules/ and build/ are host artefacts too. (cherry picked from commit bad02fb7a08a0ed0caa26bc180819a638b0386d9) --- .dockerignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.dockerignore b/.dockerignore index f5f01ce..d0478b2 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,3 +6,6 @@ README.md .gitignore .dockerignore coverage/ +vendor/ +node_modules/ +build/ From 527e04a7d6153e31eefb1405120a21f96cfae7aa Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 14:32:03 +0200 Subject: [PATCH 03/10] Apply nested #[Rules] without #[InferRules] (#31) Rules of a nested data class and of #[DataCollection] items apply when the parent is validated. Nullable, defaulted and Optional nested properties are validated only when present, at every depth. Closes #22. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 6 +- CHANGELOG.md | 17 +++ UPGRADE-3.0.md | 12 +- docs/attributes/infer-rules.md | 6 +- docs/features/validation.md | 34 +++++ src/BaseData.php | 19 ++- src/Support/ClassMeta.php | 24 +++- src/Support/ClassMetaFactory.php | 4 +- src/Support/MetadataRegistry.php | 2 +- tests/Fixtures/NestedRulesNameData.php | 16 +++ tests/Fixtures/NestedRulesParentData.php | 24 ++++ tests/Fixtures/NestedRulesTreeData.php | 17 +++ tests/Fixtures/NestedWithoutRulesData.php | 14 ++ tests/InferRulesTest.php | 13 +- tests/MetadataStateDefaultsTest.php | 4 - tests/NestedRulesTest.php | 123 ++++++++++++++++++ 16 files changed, 310 insertions(+), 25 deletions(-) create mode 100644 tests/Fixtures/NestedRulesNameData.php create mode 100644 tests/Fixtures/NestedRulesParentData.php create mode 100644 tests/Fixtures/NestedRulesTreeData.php create mode 100644 tests/Fixtures/NestedWithoutRulesData.php create mode 100644 tests/NestedRulesTest.php diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md index 7bb2b2e..fff60fd 100644 --- a/.claude/skills/migrate-from-v2-to-v3/SKILL.md +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -51,7 +51,11 @@ classes. Steps 2 and 3 only matter for classes reached through those calls. Find parents **without** `#[InferRules]` that have a property typed as a data class (or `#[DataCollection(X::class)]`) where that class, or anything it -nests, has `#[Rules]`. In 3.0 those nested rules apply. +nests, has `#[Rules]`. In 3.0 those nested rules apply: always for a +required property, and for a nullable, defaulted or `Optional` one when the +value is present as an array. Parents **with** `#[InferRules]` change only +in the other direction: an absent or `null` optional nested value no longer +fails the nested `required` rules. For each one, write a test that posts the real payload shape through the validating call site. If it now fails, **STOP AND ASK**: is the nested rule diff --git a/CHANGELOG.md b/CHANGELOG.md index 966d212..e93cb96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ## [Unreleased] +### Changed (breaking) +- The `#[Rules]` of a nested data class, and of the item class of a + `#[DataCollection]`, apply when the parent is validated by + `fromValidated()`, `validate()` or `fromValidatedResult()`, whether or not + the parent has `#[InferRules]`. In 2.x they were ignored without it (#22). + +### Fixed +- A nullable, defaulted or `Optional` nested property that is absent or + `null` no longer makes the nested class's `required` rules fail. Its + nested rules apply only when the value is present as an array, at every + depth, including self-referential classes, which 2.x validated only one + level deep. + +### Internal +- The metadata cache format is `sdo-cache-4`; files written by 2.x are + rebuilt on first use. `ClassMeta` no longer takes `inferRules`. + ## [2.9.0] — 2026-11-27 ### Fixed diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index e31b5c7..5202965 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -30,8 +30,16 @@ for Claude Code that walks a codebase through this guide class by class. `#[DataCollection]`, were checked only when the parent class had `#[InferRules]`. Without it they were ignored. -**3.0:** a nested class's rules always apply when the nested value is -present, whether or not the parent has `#[InferRules]`. +**3.0:** a nested class's rules apply whether or not the parent has +`#[InferRules]`. For a required nested property they are part of the +parent's rules (`address.zip`, `items.*.zip`). For a nullable, defaulted or +`Optional` one they apply only when the value is present as an array: an +absent or `null` value no longer fails the nested `required` rules, which +2.x did even with `#[InferRules]`. Nested classes are validated at every +depth, including self-referential ones. + +Code that reads `ClassMeta::$validationRules` sees the nested keys of +required properties only; `ClassMeta` no longer has `$inferRules`. **Affected:** a class with a property typed as another data class (or a `#[DataCollection]`) whose class has `#[Rules]`, validated through diff --git a/docs/attributes/infer-rules.md b/docs/attributes/infer-rules.md index b5bed92..9f3d2b8 100644 --- a/docs/attributes/infer-rules.md +++ b/docs/attributes/infer-rules.md @@ -76,9 +76,11 @@ public readonly TypedDataCollection $items; // 'items.*.price' => ['required', 'numeric'] ``` -The cascade only happens if the **nested** class itself has rules to contribute — a nested class without `#[InferRules]` and without any `#[Rules]` attributes contributes nothing beyond the parent's own `'field' => ['required'|'nullable', 'array']` entry. Nesting depth is unbounded (a nested class's own cascade recurses into its own nested classes), and self-referential or mutually cyclic `BaseData` graphs are detected and stop cascading at the cycle instead of recursing forever. +The cascade itself does not depend on `#[InferRules]`: a nested class's rules apply in every parent (see [Validation — Nested Data Classes](../features/validation.md#nested-data-classes)). What `#[InferRules]` on the nested class adds is its inferred rules; a nested class without `#[InferRules]` and without any `#[Rules]` contributes nothing beyond the parent's own `'field' => ['required'|'nullable', 'array']` entry. -A required [`#[Flatten]`](./flatten.md) property reads its fields from the parent's own keys, so it gets no rule for itself and the nested class's rules apply to the parent's keys without a prefix (`'zip'`, not `'address.zip'`). A nullable or defaulted flattened property keeps the prefixed form. +The keys above are static only for a required property. A nullable, defaulted or `Optional` nested property gets its nested rules at validation time, and only when its value is present as an array, so `validationRules` holds just `'field' => ['nullable', 'array']` for it. Nesting depth is unbounded, including self-referential classes. + +A required [`#[Flatten]`](./flatten.md) property reads its fields from the parent's own keys, so it gets no rule for itself and the nested class's rules apply to the parent's keys without a prefix (`'zip'`, not `'address.zip'`). A nullable or defaulted flattened property keeps the prefixed form, applied only when the prefixed key is present. ## Overriding or merging with #[Rules] diff --git a/docs/features/validation.md b/docs/features/validation.md index c87bd19..dbca078 100644 --- a/docs/features/validation.md +++ b/docs/features/validation.md @@ -43,6 +43,40 @@ class RegisterData extends BaseData } ``` +## Nested Data Classes + +The rules of a nested data class, and of the item class of a [`#[DataCollection]`](../attributes/data-collection.md), apply when the parent is validated, under a dot-prefixed key. The parent needs no `#[InferRules]` for this: + +```php +class AddressData extends BaseData +{ + public function __construct( + #[Rules(['required', 'string', 'size:5'])] + public readonly string $zip, + ) {} +} + +class CustomerData extends BaseData +{ + public function __construct( + public readonly AddressData $address, + #[DataCollection(AddressData::class)] + public readonly TypedDataCollection $shipping, + public readonly ?AddressData $billing = null, + ) {} +} + +CustomerData::fromValidated([ + 'address' => ['zip' => '123'], + 'shipping' => [['zip' => '01001'], ['zip' => '1']], +]); +// ValidationException: 'address.zip', 'shipping.1.zip' +``` + +A nested property that is nullable, has a default or is [`Optional`](./optional.md) is validated only when its value is present as an array: an absent or `null` `billing` does not make `billing.zip` required. A nested class's own nested properties follow the same rules at every depth, including self-referential classes. A [`#[Discriminator]`](../attributes/discriminator.md) base resolves to its concrete class first, and that class's rules apply. + +In 2.x the nested rules applied only when the parent had `#[InferRules]`; see [`UPGRADE-3.0.md`](https://github.com/std-out/simple-data-objects/blob/main/UPGRADE-3.0.md). + ## fromValidated() — Validate then Hydrate Throws `Illuminate\Validation\ValidationException` if validation fails; returns a hydrated instance on success. A rule that throws while evaluating the input (for example, on some Laravel versions, `max:100` on `INF` from a JSON `1e400`) is reported the same way, as a single `'$input' => ['Input could not be validated.']` error, so the response is a 422 rather than a 500. The same applies to `validate()`. diff --git a/src/BaseData.php b/src/BaseData.php index a8c4c20..1a974e3 100644 --- a/src/BaseData.php +++ b/src/BaseData.php @@ -277,8 +277,10 @@ public static function fromValidated(#[\SensitiveParameter] mixed $data): static return self::resolveDiscriminated($meta, $array)::fromValidated($array); } - if ($meta->validationRules !== []) { - self::runValidation(...$meta->validationInput($array)); + [$input, $rules] = $meta->validationInput($array); + + if ($rules !== []) { + self::runValidation($input, $rules); } return static::from($array); @@ -318,11 +320,12 @@ public static function fromValidatedResult(#[\SensitiveParameter] mixed $data): $result = static::fromResult($data); - if ($meta->validationRules === []) { + [$input, $rules] = $meta->validationInput($data); + + if ($rules === []) { return $result; } - [$input, $rules] = $meta->validationInput($data); $validator = self::validatorFactory()->make($input, $rules); try { @@ -355,12 +358,16 @@ public static function validate(#[\SensitiveParameter] mixed $data): void return; } - if ($meta->validationRules === []) { + if ($meta->validationRules === [] && ! $meta->cascadesNestedRules) { return; } $array = is_array($data) ? $data : InputNormalizer::normalize(static::class, $data); - self::runValidation(...$meta->validationInput($array)); + [$input, $rules] = $meta->validationInput($array); + + if ($rules !== []) { + self::runValidation($input, $rules); + } } /** diff --git a/src/Support/ClassMeta.php b/src/Support/ClassMeta.php index c20c9bd..f102031 100644 --- a/src/Support/ClassMeta.php +++ b/src/Support/ClassMeta.php @@ -53,7 +53,6 @@ public function __construct( public readonly bool $rejectUnknownKeys = false, public readonly ?string $wrapIn = null, public readonly array $computed = [], - public readonly bool $inferRules = false, ) { $validationRules = []; $validationAliases = []; @@ -75,11 +74,15 @@ public function __construct( $validationAliases[$inputName] = array_slice($meta->inputNames, 1); } - if ($inferRules && ($meta->nestedDataClass !== null || $meta->dataCollectionClass !== null)) { + if ($meta->nestedDataClass !== null || $meta->dataCollectionClass !== null) { $cascadesNestedRules = true; } - $nestedPrefix = $meta->flatten && ! $meta->allowsNull && ! $meta->hasDefault ? '' : "{$inputName}."; + if ($meta->allowsNull || $meta->hasDefault || $meta->isOptional) { + continue; + } + + $nestedPrefix = $meta->flatten ? '' : "{$inputName}."; foreach ($meta->nestedRules as $suffix => $rules) { $validationRules[$nestedPrefix.$suffix] = $rules; @@ -205,9 +208,23 @@ private function prepareValidation(#[\SensitiveParameter] array $data, string $p continue; } + $presenceDependent = $param->allowsNull || $param->hasDefault || $param->isOptional; + if ($param->nestedDataClass !== null) { + if ($presenceDependent) { + foreach (MetadataRegistry::get($param->nestedDataClass)->validationRules as $suffix => $keyRules) { + $rules["{$prefix}{$name}.{$suffix}"] = $keyRules; + } + } + $data[$name] = self::prepareNestedValidation($param->nestedDataClass, $data[$name], "{$prefix}{$name}.", $rules); } elseif ($param->dataCollectionClass !== null) { + if ($presenceDependent) { + foreach (MetadataRegistry::get($param->dataCollectionClass)->validationRules as $suffix => $keyRules) { + $rules["{$prefix}{$name}.*.{$suffix}"] = $keyRules; + } + } + foreach ($data[$name] as $key => $item) { if (is_array($item)) { $data[$name][$key] = self::prepareNestedValidation($param->dataCollectionClass, $item, "{$prefix}{$name}.{$key}.", $rules); @@ -258,7 +275,6 @@ public static function __set_state(array $state): self $state['rejectUnknownKeys'] ?? false, $state['wrapIn'] ?? null, $state['computed'] ?? [], - $state['inferRules'] ?? false, ); } } diff --git a/src/Support/ClassMetaFactory.php b/src/Support/ClassMetaFactory.php index 5e62071..b76cc64 100644 --- a/src/Support/ClassMetaFactory.php +++ b/src/Support/ClassMetaFactory.php @@ -98,7 +98,6 @@ private static function doBuild(string $class): ClassMeta rejectUnknownKeys: $rejectUnknownKeys, wrapIn: $wrapIn, computed: $computed, - inferRules: $inferRules, ); } @@ -132,7 +131,6 @@ private static function doBuild(string $class): ClassMeta rejectUnknownKeys: $rejectUnknownKeys, wrapIn: $wrapIn, computed: $computed, - inferRules: $inferRules, ); } @@ -382,7 +380,7 @@ enumClass: $enumClass, pipes: $paramPipes, viaConstructor: $viaConstructor, whenLoadedRelation: $whenLoadedAttrs !== [] ? $whenLoadedAttrs[0]->newInstance()->relation : null, - nestedRules: $inferRules ? RuleInferrer::cascade($nestedDataClass, $dataCollectionClass) : [], + nestedRules: RuleInferrer::cascade($nestedDataClass, $dataCollectionClass), isOptional: $isOptional, hiddenExcept: $hiddenExcept, phpType: RuleInferrer::phpTypeName($parameter), diff --git a/src/Support/MetadataRegistry.php b/src/Support/MetadataRegistry.php index c356066..5b73c17 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-3'; + private const string FORMAT = 'sdo-cache-4'; /** @var array */ private static array $cache = []; diff --git a/tests/Fixtures/NestedRulesNameData.php b/tests/Fixtures/NestedRulesNameData.php new file mode 100644 index 0000000..e4f84d4 --- /dev/null +++ b/tests/Fixtures/NestedRulesNameData.php @@ -0,0 +1,16 @@ +validationRules; $this->assertSame(['nullable', 'array'], $rules['address']); - $this->assertSame(['required', 'string', 'max:5'], $rules['address.zip']); + $this->assertArrayNotHasKey('address.zip', $rules); $this->assertArrayNotHasKey('zip', $rules); + + InferredNullableFlattenData::validate(['name' => 'Alice']); + + try { + InferredNullableFlattenData::validate(['name' => 'Alice', 'address' => ['zip' => '0100100']]); + $this->fail('Expected ValidationException'); + } catch (ValidationException $e) { + $this->assertSame(['address.street', 'address.zip'], array_keys($e->errors())); + } } public function test_required_flatten_keeps_explicitly_merged_rules_for_itself(): void diff --git a/tests/MetadataStateDefaultsTest.php b/tests/MetadataStateDefaultsTest.php index 065ecfe..f917a4c 100644 --- a/tests/MetadataStateDefaultsTest.php +++ b/tests/MetadataStateDefaultsTest.php @@ -42,7 +42,6 @@ public function test_class_meta_from_an_old_cache_gets_safe_defaults(): void $this->assertFalse($meta->rejectUnknownKeys); $this->assertNull($meta->wrapIn); $this->assertSame([], $meta->computed); - $this->assertFalse($meta->inferRules); } public function test_class_meta_state_values_override_the_defaults(): void @@ -53,14 +52,12 @@ public function test_class_meta_state_values_override_the_defaults(): void 'hasConstructor' => false, 'rejectUnknownKeys' => true, 'computed' => ['total' => 'total'], - 'inferRules' => true, ]); $this->assertSame(['P'], $meta->pipes); $this->assertFalse($meta->hasConstructor); $this->assertTrue($meta->rejectUnknownKeys); $this->assertSame(['total' => 'total'], $meta->computed); - $this->assertTrue($meta->inferRules); } public function test_class_meta_constructor_defaults(): void @@ -68,7 +65,6 @@ public function test_class_meta_constructor_defaults(): void $meta = new ClassMeta([]); $this->assertFalse($meta->rejectUnknownKeys); - $this->assertFalse($meta->inferRules); $this->assertTrue($meta->hasConstructor); } diff --git a/tests/NestedRulesTest.php b/tests/NestedRulesTest.php new file mode 100644 index 0000000..8b2b88d --- /dev/null +++ b/tests/NestedRulesTest.php @@ -0,0 +1,123 @@ +validationRules; + + $this->assertSame(['required', 'string', 'min:5'], $rules['required.name']); + $this->assertSame(['required', 'string', 'min:5'], $rules['items.*.name']); + $this->assertArrayNotHasKey('nullable.name', $rules); + $this->assertArrayNotHasKey('optional.name', $rules); + $this->assertArrayNotHasKey('nullableItems.*.name', $rules); + $this->assertArrayNotHasKey('defaulted.name', $rules); + } + + public function test_only_classes_with_nested_data_cascade(): void + { + $this->assertTrue(MetadataRegistry::get(NestedRulesParentData::class)->cascadesNestedRules); + $this->assertFalse(MetadataRegistry::get(UserData::class)->cascadesNestedRules); + } + + public function test_absent_or_null_optional_nested_values_are_not_validated(): void + { + $data = NestedRulesParentData::fromValidated([ + 'required' => ['name' => 'Alice'], + 'items' => [], + 'nullable' => null, + ]); + + $this->assertNull($data->nullable); + $this->assertNull($data->nullableItems); + $this->assertSame('Alice', $data->defaulted->name); + } + + /** @return iterable, list}> */ + public static function invalidNestedInput(): iterable + { + $valid = ['required' => ['name' => 'Alice'], 'items' => []]; + + yield 'required' => [['required' => ['name' => 'ab'], 'items' => []], ['required.name']]; + yield 'collection item' => [[...$valid, 'items' => [['name' => 'Alice'], ['name' => 'ab']]], ['items.1.name']]; + yield 'present nullable' => [[...$valid, 'nullable' => ['name' => 'ab']], ['nullable.name']]; + yield 'present optional' => [[...$valid, 'optional' => []], ['optional.name']]; + yield 'present defaulted' => [[...$valid, 'defaulted' => ['name' => 'ab']], ['defaulted.name']]; + yield 'present nullable collection item' => [[...$valid, 'nullableItems' => [['name' => 'ab']]], ['nullableItems.0.name']]; + } + + /** + * @param array $input + * @param list $errorKeys + */ + #[DataProvider('invalidNestedInput')] + public function test_nested_rules_apply_without_infer_rules(array $input, array $errorKeys): void + { + try { + NestedRulesParentData::fromValidated($input); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame($errorKeys, array_keys($e->errors())); + } + + $this->assertSame($errorKeys, array_keys(NestedRulesParentData::fromValidatedResult($input)->errors())); + } + + public function test_nested_rules_apply_at_every_depth_of_a_self_referential_class(): void + { + $input = ['name' => 'leaf', 'parent' => ['name' => 'mid', 'parent' => ['name' => 'r']]]; + + try { + NestedRulesTreeData::validate($input); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame(['parent.parent.name'], array_keys($e->errors())); + } + } + + public function test_nested_discriminated_value_is_validated_against_the_concrete_class_rules(): void + { + try { + OrderWithPaymentData::fromValidated(['id' => 'o-1', 'payment' => ['type' => 'card', 'amount' => 1, 'last4' => '1']]); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame(['payment.last4'], array_keys($e->errors())); + } + } + + public function test_nested_classes_without_rules_skip_validation(): void + { + $input = ['user' => ['name' => 'Alice', 'email' => 'alice@example.com']]; + + NestedWithoutRulesData::validate($input); + + $this->assertSame('Alice', NestedWithoutRulesData::fromValidated($input)->user->name); + $this->assertTrue(NestedWithoutRulesData::fromValidatedResult($input)->ok()); + } + + public function test_validate_on_a_class_without_rules_ignores_input_it_could_not_normalize(): void + { + UserData::validate(42); + + $this->addToAssertionCount(1); + } +} From 4633d0ab17547f8dc8a63f589f7942fbeff20468 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:05:02 +0200 Subject: [PATCH 04/10] Run pipes before validation (#32) fromValidated(), validate() and fromValidatedResult() pipe the input once, validate the piped values and hydrate them with a pipe-less hydrator compiled on first use. A failing pipe is a validation error. from() is unchanged. Closes #23. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 5 +- CHANGELOG.md | 8 + UPGRADE-3.0.md | 8 +- docs/features/error-accumulation.md | 2 +- docs/features/pipes.md | 23 +++ docs/features/validation.md | 2 +- src/BaseData.php | 111 ++++++++++--- src/Support/ClassMeta.php | 84 ++++++++++ src/Support/HydratorCompiler.php | 76 ++++++--- tests/Fixtures/ClassAndFlattenPipedData.php | 23 +++ tests/Fixtures/CommaSplitValuePipe.php | 19 +++ tests/Fixtures/CountingArrayValuePipe.php | 19 +++ tests/Fixtures/FlattenPipedData.php | 18 +++ tests/Fixtures/NoConstructorPipedData.php | 17 ++ tests/Fixtures/ThrowingValuePipe.php | 15 ++ tests/Fixtures/ThrowingValuePipeData.php | 19 +++ tests/Fixtures/ValidatedPipedData.php | 27 ++++ tests/PipesBeforeValidationTest.php | 148 ++++++++++++++++++ 18 files changed, 574 insertions(+), 50 deletions(-) create mode 100644 tests/Fixtures/ClassAndFlattenPipedData.php create mode 100644 tests/Fixtures/CommaSplitValuePipe.php create mode 100644 tests/Fixtures/CountingArrayValuePipe.php create mode 100644 tests/Fixtures/FlattenPipedData.php create mode 100644 tests/Fixtures/NoConstructorPipedData.php create mode 100644 tests/Fixtures/ThrowingValuePipe.php create mode 100644 tests/Fixtures/ThrowingValuePipeData.php create mode 100644 tests/Fixtures/ValidatedPipedData.php create mode 100644 tests/PipesBeforeValidationTest.php diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md index fff60fd..cd12d8e 100644 --- a/.claude/skills/migrate-from-v2-to-v3/SKILL.md +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -73,7 +73,10 @@ Find classes with both `#[Pipe]` (class or property) and rules. For each pipe: - **The pipe now sees unvalidated input.** Read its `handle()`; if it assumes a type (calls `trim()`, `explode()`, indexes an array), make it pass other types through unchanged (`is_string($value) ? trim($value) : $value`). - A pipe that throws becomes a validation error under `'$pipeline'`. + A pipe that throws becomes a validation error under `'$pipeline'` (class + pipe) or the property's key (property pipe). +- Pipes on `#[Flatten]` properties and inside nested data classes still run + after validation; nothing to change for them. Add a test with input that only passes after the pipe (e.g. `' abc '` for `min:3` + trim) and one that the pipe cannot handle (e.g. an array). diff --git a/CHANGELOG.md b/CHANGELOG.md index e93cb96..fd00fd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `fromValidated()`, `validate()` or `fromValidatedResult()`, whether or not the parent has `#[InferRules]`. In 2.x they were ignored without it (#22). +- `fromValidated()`, `validate()` and `fromValidatedResult()` run the class + and property pipes before validation, validate the piped values and + hydrate from them without running the pipes again. In 2.x the rules saw + the raw input and the pipes ran afterwards. A pipe that throws is a + validation error under `'$pipeline'` (class pipe) or the property's key. + `#[RejectUnknownKeys]` still checks the raw input; `from()` is unchanged + (#23). + ### Fixed - A nullable, defaulted or `Optional` nested property that is absent or `null` no longer makes the nested class's `required` rules fail. Its diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index 5202965..0d49948 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -57,7 +57,9 @@ pipes. `' ab '` passed `min:3` and was trimmed to `'ab'` afterwards. **3.0:** `fromValidated()`, `validate()` and `fromValidatedResult()` run the class and property pipes first, validate the piped values, and hydrate from -them without running the pipes again. `from()` is unchanged. +them without running the pipes again. `#[RejectUnknownKeys]` still checks +the raw input. Pipes on a `#[Flatten]` property and pipes of nested data +classes still run at hydration, after validation. `from()` is unchanged. **Affected:** any class with both `#[Pipe]` and `#[Rules]` (or `#[InferRules]`). @@ -68,7 +70,9 @@ them without running the pipes again. `from()` is unchanged. turns `"1,2"` into `[1, 2]` now needs an `array` rule, not a `string` rule. - A pipe now sees invalid input before any rule rejects it. Make it return unexpected types unchanged instead of failing on them. A pipe that still - throws is reported as a validation error under `'$pipeline'`. + throws is reported as a validation error: under `'$pipeline'` for a class + pipe, under the property's input key for a property pipe, with the + message `Input could not be processed.` ## Scalar properties are coerced without loss diff --git a/docs/features/error-accumulation.md b/docs/features/error-accumulation.md index 472c2e7..b7ce818 100644 --- a/docs/features/error-accumulation.md +++ b/docs/features/error-accumulation.md @@ -55,7 +55,7 @@ $result->errors(); ## fromValidatedResult() — merge in Rules validation too -Runs `fromResult()` and, if the class declares `#[Rules]` (or [`#[InferRules]`](../attributes/infer-rules.md)), also validates the raw input and merges in the first message per failing rule. A validation message wins over a hydration message on the same key. +Runs `fromResult()` and, if the class declares `#[Rules]` (or [`#[InferRules]`](../attributes/infer-rules.md)), also validates the input and merges in the first message per failing rule. A class with [pipes](./pipes.md#pipes-and-validation) is piped once, then validated and hydrated from the piped values. A validation message wins over a hydration message on the same key. ```php $result = OrderData::fromValidatedResult($request->all()); diff --git a/docs/features/pipes.md b/docs/features/pipes.md index c0b3b45..ac11ac6 100644 --- a/docs/features/pipes.md +++ b/docs/features/pipes.md @@ -113,6 +113,29 @@ For each property: typed property value ``` +## Pipes and Validation + +`fromValidated()`, `validate()` and `fromValidatedResult()` run the class pipes and the property pipes **before** validation, check the `#[Rules]` against the piped values, and hydrate from those values without running the pipes again: + +```php +class SignupData extends BaseData +{ + public function __construct( + #[Pipe(TrimValuePipe::class)] + #[Rules(['required', 'string', 'min:3'])] + public readonly string $name, + ) {} +} + +SignupData::fromValidated(['name' => ' ab ']); // ValidationException: 'ab' is shorter than 3 +``` + +Write rules for the value a pipe produces, not the raw input. A pipe that turns `"a,b"` into `['a', 'b']` needs an `array` rule. + +Because pipes now see the input before any rule rejects it, a pipe should return values of an unexpected type unchanged (`is_string($value) ? trim($value) : $value`) instead of failing on them. A pipe that throws is reported as a validation error: a class pipe under `'$pipeline'`, a property pipe under the property's input key, with the message `Input could not be processed.` (`fromValidatedResult()` reports the pipe's own message, like `fromResult()`). + +`#[RejectUnknownKeys]` is still checked against the keys of the raw input. Pipes on a [`#[Flatten]`](../attributes/flatten.md) property and pipes of nested data classes run when that object is hydrated, after validation. `from()` is unchanged: it runs the pipes and never validates. + ## Built-in Pipes | Class | Type | Effect | diff --git a/docs/features/validation.md b/docs/features/validation.md index dbca078..97ee0b5 100644 --- a/docs/features/validation.md +++ b/docs/features/validation.md @@ -79,7 +79,7 @@ In 2.x the nested rules applied only when the parent had `#[InferRules]`; see [` ## fromValidated() — Validate then Hydrate -Throws `Illuminate\Validation\ValidationException` if validation fails; returns a hydrated instance on success. A rule that throws while evaluating the input (for example, on some Laravel versions, `max:100` on `INF` from a JSON `1e400`) is reported the same way, as a single `'$input' => ['Input could not be validated.']` error, so the response is a 422 rather than a 500. The same applies to `validate()`. +Runs the [pipes](./pipes.md#pipes-and-validation), validates the piped values, then hydrates them. Throws `Illuminate\Validation\ValidationException` if validation fails; returns a hydrated instance on success. A rule that throws while evaluating the input (for example, on some Laravel versions, `max:100` on `INF` from a JSON `1e400`) is reported the same way, as a single `'$input' => ['Input could not be validated.']` error, so the response is a 422 rather than a 500. The same applies to `validate()`. ```php use Illuminate\Validation\ValidationException; diff --git a/src/BaseData.php b/src/BaseData.php index 1a974e3..b266a5e 100644 --- a/src/BaseData.php +++ b/src/BaseData.php @@ -277,13 +277,20 @@ public static function fromValidated(#[\SensitiveParameter] mixed $data): static return self::resolveDiscriminated($meta, $array)::fromValidated($array); } - [$input, $rules] = $meta->validationInput($array); + $piped = self::validatedInput($meta, $array); - if ($rules !== []) { - self::runValidation($input, $rules); + if (! $meta->pipesBeforeValidation) { + return static::from($piped); + } + + if ($meta->rejectUnknownKeys && ($unknown = $meta->unknownKeys($array)) !== []) { + throw DataHydrationException::unknownKeys(static::class, $unknown); } - return static::from($array); + $hydrate = HydratorCompiler::$pipelessHydrators[static::class] ?? HydratorCompiler::compilePipeless(static::class); + + /** @var static */ + return $hydrate($piped); } /** @@ -318,31 +325,31 @@ public static function fromValidatedResult(#[\SensitiveParameter] mixed $data): return $target::fromValidatedResult($data); } - $result = static::fromResult($data); - - [$input, $rules] = $meta->validationInput($data); - - if ($rules === []) { - return $result; - } + $pipeErrors = []; - $validator = self::validatorFactory()->make($input, $rules); + if ($meta->pipesBeforeValidation) { + [$piped, $pipeErrors] = $meta->runPipes($data, static::class); - try { - if (! $validator->fails()) { - return $result; + if (isset($pipeErrors['$pipeline'])) { + return HydrationResult::failure($pipeErrors); } - } catch (\Throwable) { - return HydrationResult::failure([...$result->errors(), '$input' => 'Input could not be validated.']); - } - $validationErrors = []; + if ($meta->rejectUnknownKeys && ($unknown = $meta->unknownKeys($data)) !== []) { + $pipeErrors['$unknown'] = DataHydrationException::unknownKeys(static::class, $unknown)->getMessage(); + } - foreach ($validator->errors()->messages() as $key => $messages) { - $validationErrors[$key] = $messages[0]; + $data = $piped; + $collect = HydratorCompiler::$pipelessCollectingHydrators[static::class] ?? HydratorCompiler::compilePipelessCollecting(static::class); + /** @var HydrationResult $result */ + $result = $collect($data); + } else { + $result = static::fromResult($data); } - return HydrationResult::failure([...$result->errors(), ...$validationErrors]); + [$input, $rules] = $meta->validationInput($data); + $errors = $rules === [] ? $pipeErrors : [...$pipeErrors, ...self::validationErrors($input, $rules)]; + + return $errors === [] ? $result : HydrationResult::failure([...$result->errors(), ...$errors]); } /** @throws ValidationException */ @@ -358,16 +365,70 @@ public static function validate(#[\SensitiveParameter] mixed $data): void return; } - if ($meta->validationRules === [] && ! $meta->cascadesNestedRules) { + if ($meta->validationRules === [] && ! $meta->cascadesNestedRules && ! $meta->pipesBeforeValidation) { return; } - $array = is_array($data) ? $data : InputNormalizer::normalize(static::class, $data); - [$input, $rules] = $meta->validationInput($array); + self::validatedInput($meta, is_array($data) ? $data : InputNormalizer::normalize(static::class, $data)); + } + + /** + * Pipes the input, validates the piped values and returns them. + * + * @param array $data + * @return array + * + * @throws ValidationException + */ + private static function validatedInput(ClassMeta $meta, #[\SensitiveParameter] array $data): array + { + if ($meta->pipesBeforeValidation) { + [$data, $pipeErrors] = $meta->runPipes($data, static::class); + + if ($pipeErrors !== []) { + $validator = self::validatorFactory()->make([], []); + + foreach (array_keys($pipeErrors) as $key) { + $validator->errors()->add((string) $key, 'Input could not be processed.'); + } + + throw new ValidationException($validator); + } + } + + [$input, $rules] = $meta->validationInput($data); if ($rules !== []) { self::runValidation($input, $rules); } + + return $data; + } + + /** + * @param array $input + * @param array $rules + * @return array + */ + private static function validationErrors(#[\SensitiveParameter] array $input, array $rules): array + { + $validator = self::validatorFactory()->make($input, $rules); + + try { + if (! $validator->fails()) { + return []; + } + } catch (\Throwable) { + return ['$input' => 'Input could not be validated.']; + } + + $errors = []; + + foreach ($validator->errors()->messages() as $key => $messages) { + $errors[$key] = $messages[0]; + } + + return $errors; } /** diff --git a/src/Support/ClassMeta.php b/src/Support/ClassMeta.php index f102031..6d9058a 100644 --- a/src/Support/ClassMeta.php +++ b/src/Support/ClassMeta.php @@ -33,6 +33,8 @@ final class ClassMeta public readonly bool $cascadesNestedRules; + public readonly bool $pipesBeforeValidation; + /** @var array */ public readonly array $sensitiveFields; @@ -95,10 +97,92 @@ public function __construct( $this->cascadesNestedRules = $cascadesNestedRules; $this->sensitiveFields = $sensitiveFields; $this->pipes = $pipes; + $this->pipesBeforeValidation = $pipes !== [] || array_any($parameters, static fn (ParameterMeta $p): bool => $p->pipes !== [] && ! $p->flatten); $this->hasConstructor = $hasConstructor; $this->hasExtraProperties = $hasConstructor && array_any($parameters, static fn (ParameterMeta $p): bool => ! $p->viaConstructor); } + /** @return array */ + public function knownKeys(): array + { + $known = []; + + foreach ($this->parameters as $param) { + foreach ($param->inputNames as $name) { + $known[$name] = true; + } + } + + foreach ($this->computed as $key) { + $known[$key] = true; + } + + return $known; + } + + /** + * @param array $data + * @return list + */ + public function unknownKeys(#[\SensitiveParameter] array $data): array + { + return array_map(strval(...), array_keys(array_diff_key($data, $this->knownKeys()))); + } + + /** + * Runs the class pipes, then each property's pipes on the first input + * key present for it. #[Flatten] properties keep their pipes for + * hydration, since they read the whole input. + * + * @param class-string $class + * @param array $data + * @return array{0: array, 1: array} piped input and errors by key + */ + public function runPipes(#[\SensitiveParameter] array $data, string $class): array + { + try { + $data = PipelineRunner::run($data, $class, $this->pipes); + } catch (\Throwable $e) { + return [$data, ['$pipeline' => $e->getMessage()]]; + } + + $errors = []; + + foreach ($this->parameters as $param) { + if ($param->pipes === [] || $param->flatten) { + continue; + } + + foreach ($param->inputNames as $name) { + if (! array_key_exists($name, $data)) { + continue; + } + + try { + $data[$name] = PipelineRunner::runOnValue($data[$name], $param->phpName, $param->pipes); + } catch (\Throwable $e) { + $errors[$param->inputNames[0]] = $e->getMessage(); + } + + break; + } + } + + return [$data, $errors]; + } + + public function withoutPipes(): self + { + return self::__set_state([ + 'parameters' => array_map( + static fn (ParameterMeta $p): ParameterMeta => $p->flatten ? $p : ParameterMeta::__set_state(['pipes' => []] + get_object_vars($p)), + $this->parameters, + ), + 'pipes' => [], + 'rejectUnknownKeys' => false, + ] + get_object_vars($this)); + } + /** * Missing and unmapped discriminator values resolve to the configured * fallback, or null when there is none. diff --git a/src/Support/HydratorCompiler.php b/src/Support/HydratorCompiler.php index 9a877b2..8e4a83e 100644 --- a/src/Support/HydratorCompiler.php +++ b/src/Support/HydratorCompiler.php @@ -61,6 +61,20 @@ final class HydratorCompiler */ public static array $collectingHydrators = []; + /** + * @internal Read directly by BaseData's validating factories — do not mutate. + * + * @var array): object> + */ + public static array $pipelessHydrators = []; + + /** + * @internal Read directly by BaseData::fromValidatedResult() — do not mutate. + * + * @var array): HydrationResult> + */ + public static array $pipelessCollectingHydrators = []; + /** @param class-string $class */ public static function compile(string $class): Closure { @@ -145,12 +159,52 @@ public static function compileCollecting(string $class): Closure return self::$collectingHydrators[$class] = $needsBinding ? Closure::bind($fn, null, $class) : $fn; } + /** + * Hydrates input the validating factories already piped, so pipes do not + * run twice. Compiled on first use, only for classes with pipes. + * + * @param class-string $class + * @return Closure(array): object + */ + public static function compilePipeless(string $class): Closure + { + $meta = MetadataRegistry::get($class)->withoutPipes(); + $p = $meta->parameters; + $pipes = $meta->pipes; + + $fn = eval('return '.self::generate($class, $meta).';'); + + return self::$pipelessHydrators[$class] = self::bindForAssignments($fn, $meta, $class); + } + + /** + * @param class-string $class + * @return Closure(array): HydrationResult + */ + public static function compilePipelessCollecting(string $class): Closure + { + $meta = MetadataRegistry::get($class)->withoutPipes(); + $p = $meta->parameters; + $pipes = $meta->pipes; + + $fn = eval('return '.self::generateCollecting($class, $meta).';'); + + return self::$pipelessCollectingHydrators[$class] = self::bindForAssignments($fn, $meta, $class); + } + public static function flush(): void { self::$hydrators = []; self::$argResolvers = []; self::$populators = []; self::$collectingHydrators = []; + self::$pipelessHydrators = []; + self::$pipelessCollectingHydrators = []; + } + + private static function bindForAssignments(Closure $fn, ClassMeta $meta, string $class): Closure + { + return ! $meta->hasConstructor || $meta->hasExtraProperties ? Closure::bind($fn, null, $class) : $fn; } /** @@ -259,31 +313,13 @@ private static function buildUnknownKeysCheck(string $class, ClassMeta $meta): s } $classExport = var_export($class, true); - $knownKeys = self::knownKeysExport($meta); + $knownKeys = var_export($meta->knownKeys(), true); return " if (\$u = \\array_diff_key(\$d, {$knownKeys})) {\n" ." throw \\StdOut\\SimpleDataObjects\\Exceptions\\DataHydrationException::unknownKeys({$classExport}, \\array_keys(\$u));\n" ." }\n"; } - /** Every accepted input alias and every #[Computed] output key, as a var_export'd set. */ - private static function knownKeysExport(ClassMeta $meta): string - { - $known = []; - - foreach ($meta->parameters as $param) { - foreach ($param->inputNames as $name) { - $known[$name] = true; - } - } - - foreach ($meta->computed as $key) { - $known[$key] = true; - } - - return var_export($known, true); - } - /** * The single source of hydration-argument semantics — both closure * flavors are assembled from this output. @@ -529,7 +565,7 @@ private static function buildCollectingUnknownCheck(string $class, ClassMeta $me } $classExport = var_export($class, true); - $knownKeys = self::knownKeysExport($meta); + $knownKeys = var_export($meta->knownKeys(), true); return " if (\$u = \\array_diff_key(\$d, {$knownKeys})) {\n" ." \$errors['\$unknown'] = \\StdOut\\SimpleDataObjects\\Exceptions\\DataHydrationException::unknownKeys({$classExport}, \\array_keys(\$u))->getMessage();\n" diff --git a/tests/Fixtures/ClassAndFlattenPipedData.php b/tests/Fixtures/ClassAndFlattenPipedData.php new file mode 100644 index 0000000..16159cf --- /dev/null +++ b/tests/Fixtures/ClassAndFlattenPipedData.php @@ -0,0 +1,23 @@ + $tags */ + public function __construct( + #[Rules(['required', 'string', 'min:3'])] + public readonly string $name, + #[MapInputName('tags', 'labels')] + #[Pipe(CommaSplitValuePipe::class)] + #[Rules(['array', 'min:2'])] + public readonly array $tags = [], + ) {} +} diff --git a/tests/PipesBeforeValidationTest.php b/tests/PipesBeforeValidationTest.php new file mode 100644 index 0000000..f60d05e --- /dev/null +++ b/tests/PipesBeforeValidationTest.php @@ -0,0 +1,148 @@ + ' ab ']); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame(['name'], array_keys($e->errors())); + } + + $this->assertSame(['name'], array_keys(ValidatedPipedData::fromValidatedResult(['name' => ' ab '])->errors())); + $this->assertSame(['name', 'tags'], array_keys(ValidatedPipedData::fromValidatedResult(['name' => 'ab', 'tags' => 'a'])->errors())); + } + + public function test_piped_values_are_validated_and_hydrated_with_each_pipe_run_once(): void + { + $data = ValidatedPipedData::fromValidated(['name' => ' abc ', 'tags' => 'a,b']); + + $this->assertSame('abc', $data->name); + $this->assertSame(['a', 'b'], $data->tags); + $this->assertSame(1, CommaSplitValuePipe::$calls); + + $result = ValidatedPipedData::fromValidatedResult(['name' => ' abc ', 'labels' => 'a,b']); + + $this->assertSame(['a', 'b'], $result->value()->tags); + $this->assertSame(2, CommaSplitValuePipe::$calls); + + $this->assertSame(['a', 'b'], ValidatedPipedData::fromValidated(['name' => 'abc', 'tags' => 'a,b', 'labels' => 'c,d'])->tags); + $this->assertSame(3, CommaSplitValuePipe::$calls); + } + + public function test_validate_runs_the_pipes_first(): void + { + ValidatedPipedData::validate(['name' => 'abc', 'labels' => 'a,b']); + + $this->expectException(ValidationException::class); + + ValidatedPipedData::validate(['name' => 'abc', 'labels' => 'a']); + } + + public function test_unknown_keys_are_checked_against_the_raw_input(): void + { + try { + ValidatedPipedData::fromValidated(['name' => 'abc', 'extra' => 1]); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertSame(['extra'], $e->unknownKeys); + } + + $this->assertSame(['$unknown'], array_keys(ValidatedPipedData::fromValidatedResult(['name' => 'abc', 'extra' => 1])->errors())); + + try { + ValidatedPipedData::fromValidated(['name' => 'abc', 7 => 'x']); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertSame(['7'], $e->unknownKeys); + } + } + + public function test_a_failing_class_pipe_is_a_pipeline_error(): void + { + try { + ThrowingPipeData::fromValidated(['name' => 'Alice']); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame(['$pipeline' => ['Input could not be processed.']], $e->errors()); + } + + $this->assertSame(['$pipeline' => 'pipe exploded'], ThrowingPipeData::fromValidatedResult(['name' => 'Alice'])->errors()); + $this->assertSame(['$pipeline' => 'pipe exploded'], ThrowingPipeData::fromValidatedResult([])->errors()); + } + + public function test_a_failing_property_pipe_is_reported_under_the_field(): void + { + try { + ThrowingValuePipeData::validate(['name' => 'Alice', 'nickname' => 'Al']); + $this->fail('Expected a ValidationException.'); + } catch (ValidationException $e) { + $this->assertSame(['nickname' => ['Input could not be processed.']], $e->errors()); + } + + $this->assertSame(['nickname' => 'value pipe exploded'], ThrowingValuePipeData::fromValidatedResult(['name' => 'Alice', 'nickname' => 'Al'])->errors()); + $this->assertSame(['name' => 'validation.required', 'nickname' => 'value pipe exploded'], ThrowingValuePipeData::fromValidatedResult(['nickname' => 'Al'])->errors()); + $this->assertNull(ThrowingValuePipeData::fromValidated(['name' => 'Alice'])->nickname); + } + + public function test_flattened_property_pipes_run_once_at_hydration(): void + { + $this->assertFalse(MetadataRegistry::get(FlattenPipedData::class)->pipesBeforeValidation); + $this->assertTrue(MetadataRegistry::get(ClassAndFlattenPipedData::class)->pipesBeforeValidation); + + $data = ClassAndFlattenPipedData::fromValidated(['code' => ' abc ', 'user' => 'ignored', 'name' => 'Alice', 'email' => 'a@example.com']); + + $this->assertSame('abc', $data->code); + $this->assertSame('Alice', $data->user->name); + $this->assertSame(1, CountingArrayValuePipe::$calls); + } + + public function test_classes_with_assigned_properties_hydrate_the_piped_input(): void + { + $hybrid = HybridPipedData::fromValidated(['name' => ' Alice ', 'bio' => '']); + + $this->assertSame('Alice', $hybrid->name); + $this->assertNull($hybrid->bio); + $this->assertNull(HybridPipedData::fromValidatedResult(['name' => 'Alice', 'bio' => ' '])->value()->bio); + + $this->assertSame('abc', NoConstructorPipedData::fromValidated(['name' => ' abc '])->name); + $this->assertSame(['name'], array_keys(NoConstructorPipedData::fromValidatedResult(['name' => ' ab '])->errors())); + } + + public function test_classes_without_pipes_or_rules_skip_validation(): void + { + $this->assertFalse(MetadataRegistry::get(UserData::class)->pipesBeforeValidation); + + UserData::validate(42); + + $this->addToAssertionCount(1); + } +} From d7990f2fa95e030948e885883e44f499723c8677 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:30:25 +0200 Subject: [PATCH 05/10] Throw on an invalid enum value for a nullable property (#33) * Throw on an invalid enum value for a nullable property A non-null value that matches no case throws DataHydrationException whether the property is nullable or not. EnumCast without a default keeps the old behaviour. Closes #25. * Flush metadata before the service provider cache path tests The cache file is written only when metadata is built, so the test failed when an earlier test had already loaded UserData. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 4 ++-- CHANGELOG.md | 6 ++++++ UPGRADE-3.0.md | 4 +++- docs/casts/enum.md | 6 +++--- docs/features/hydration.md | 4 ++-- src/Support/ValueCaster.php | 8 ++------ tests/CastsTest.php | 5 +++++ tests/HydrationTest.php | 15 +++++++++------ tests/ServiceProviderTest.php | 2 ++ 9 files changed, 34 insertions(+), 20 deletions(-) diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md index cd12d8e..9de71b9 100644 --- a/.claude/skills/migrate-from-v2-to-v3/SKILL.md +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -103,8 +103,8 @@ pass without asking. Find nullable enum properties (`?Status`, `Status|null`). An unknown value now throws instead of becoming `null`. If clients send unknown values on purpose (e.g. forward compatibility), **STOP AND ASK** — the options are a -rule (`Rule::enum`) that rejects them with a message, or a pipe that maps -them to `null` explicitly. +rule (`Rule::enum`) that rejects them with a message, or +`#[Cast(new EnumCast(Status::class))]`, which maps them to `null` as 2.x did. ## Step 6 — exceptions from hydration diff --git a/CHANGELOG.md b/CHANGELOG.md index fd00fd9..907bc59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,8 +20,14 @@ 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 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(...))]` + keeps the old behaviour (#25). ### Fixed +- The `EnumCast` docs named its second argument `fallback`; it is + `default`. - A nullable, defaulted or `Optional` nested property that is absent or `null` no longer makes the nested class's `required` rules fail. Its nested rules apply only when the value is present as an array, at every diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index 0d49948..1c609b5 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -109,7 +109,9 @@ property; a non-nullable property already threw. `DataHydrationException`. `null` stays `null`. **What to do:** send `null` (or omit the key with a default) instead of an -unknown value, or validate the value with a rule first. +unknown value, or validate the value with a rule first. To keep the 2.x +behaviour for a property, add `#[Cast(new EnumCast(Status::class))]`: it +turns unknown values into `null`. ## Casts throw `DataHydrationException` diff --git a/docs/casts/enum.md b/docs/casts/enum.md index bf1e96f..6777f91 100644 --- a/docs/casts/enum.md +++ b/docs/casts/enum.md @@ -41,18 +41,18 @@ Use `EnumCast` explicitly when you need a fallback value. ## With a Fallback ```php -#[Cast(new EnumCast(Status::class, fallback: Status::Inactive))] +#[Cast(new EnumCast(Status::class, default: Status::Inactive))] public readonly Status $status, ``` -If the input value does not match any enum case, `Status::Inactive` is returned instead of throwing. +If the input value does not match any enum case, `Status::Inactive` is returned instead of throwing. Without `default`, `null` and unknown values become `null`, so the property must be nullable. ## Constructor Parameters ```php new EnumCast( enumClass: Status::class, - fallback: null, // ?BackedEnum, default null = throw on unknown value + default: null, // ?UnitEnum returned for null and unknown values ) ``` diff --git a/docs/features/hydration.md b/docs/features/hydration.md index afc8747..841d43d 100644 --- a/docs/features/hydration.md +++ b/docs/features/hydration.md @@ -138,14 +138,14 @@ Already-instantiated enum values pass through unchanged. ### Invalid Enum Values -A value that matches no case throws a `DataHydrationException` with the field name for a **required** parameter, and resolves to `null` for a **nullable** one: +A non-null value that matches no case throws a `DataHydrationException` with the field name, whether the parameter is required or nullable. `null` on a nullable parameter stays `null`: ```php OrderData::from(['status' => 'bogus', 'priority' => 'High']); // throws DataHydrationException: Invalid value 'bogus' for field 'status'; expected a case of Status. ``` -For a fallback value instead of an exception, use [`EnumCast`](../casts/enum.md). +For a fallback value instead of an exception, use [`EnumCast`](../casts/enum.md). `#[Cast(new EnumCast(Status::class))]` on a `?Status` property turns unknown values into `null`, as 2.x did without a cast. ## Lazy Hydration diff --git a/src/Support/ValueCaster.php b/src/Support/ValueCaster.php index b886927..5b968af 100644 --- a/src/Support/ValueCaster.php +++ b/src/Support/ValueCaster.php @@ -49,7 +49,7 @@ public static function castSensitive(ParameterMeta $meta, #[\SensitiveParameter] } } - private static function castEnum(ParameterMeta $meta, #[\SensitiveParameter] mixed $value): ?UnitEnum + private static function castEnum(ParameterMeta $meta, #[\SensitiveParameter] mixed $value): UnitEnum { $enum = null; @@ -67,10 +67,6 @@ private static function castEnum(ParameterMeta $meta, #[\SensitiveParameter] mix } } - if ($enum === null && ! $meta->allowsNull) { - throw DataHydrationException::invalidEnumValue($meta->enumClass, (string) $meta->inputNames[0], $value); - } - - return $enum; + return $enum ?? throw DataHydrationException::invalidEnumValue($meta->enumClass, (string) $meta->inputNames[0], $value); } } diff --git a/tests/CastsTest.php b/tests/CastsTest.php index 71cdf65..a3ec6df 100644 --- a/tests/CastsTest.php +++ b/tests/CastsTest.php @@ -138,6 +138,11 @@ public function test_enum_cast_falls_back_to_default_on_null(): void $this->assertSame(Status::Inactive, $cast->get(null)); } + public function test_enum_cast_without_default_turns_unknown_values_into_null(): void + { + $this->assertNull(new EnumCast(Status::class)->get('bogus')); + } + public function test_enum_cast_passes_through_existing_enum(): void { $cast = new EnumCast(Status::class, Status::Inactive); diff --git a/tests/HydrationTest.php b/tests/HydrationTest.php index a0a271f..7da0cbb 100644 --- a/tests/HydrationTest.php +++ b/tests/HydrationTest.php @@ -282,11 +282,14 @@ public function test_non_scalar_enum_value_for_required_field_throws(): void OrderData::from(['id' => 1, 'status' => ['nested']]); } - public function test_invalid_enum_value_for_nullable_field_resolves_to_null(): void + public function test_invalid_enum_value_for_nullable_field_throws(): void { - $order = OrderData::from(['id' => 1, 'status' => 'active', 'previousStatus' => 'bogus']); + $this->assertNull(OrderData::from(['id' => 1, 'status' => 'active', 'previousStatus' => null])->previousStatus); + $this->assertSame(['previousStatus'], array_keys(OrderData::fromResult(['id' => 1, 'status' => 'active', 'previousStatus' => 'bogus'])->errors())); - $this->assertNull($order->previousStatus); + $this->expectException(DataHydrationException::class); + + OrderData::from(['id' => 1, 'status' => 'active', 'previousStatus' => 'bogus']); } public function test_pure_enum_hydrated_from_case_name(): void @@ -304,10 +307,10 @@ public function test_pure_enum_invalid_case_name_throws(): void TicketData::from(['title' => 'Bug', 'priority' => 'Urgent']); } - public function test_pure_enum_invalid_value_for_nullable_field_resolves_to_null(): void + public function test_pure_enum_invalid_value_for_nullable_field_throws(): void { - $ticket = TicketData::from(['title' => 'Bug', 'priority' => 'Low', 'fallbackPriority' => 'Nope']); + $this->expectException(DataHydrationException::class); - $this->assertNull($ticket->fallbackPriority); + TicketData::from(['title' => 'Bug', 'priority' => 'Low', 'fallbackPriority' => 'Nope']); } } diff --git a/tests/ServiceProviderTest.php b/tests/ServiceProviderTest.php index 71507f6..d80b046 100644 --- a/tests/ServiceProviderTest.php +++ b/tests/ServiceProviderTest.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Artisan; use StdOut\SimpleDataObjects\Laravel\SimpleDataObjectsServiceProvider; +use StdOut\SimpleDataObjects\Support\MetadataRegistry; use StdOut\SimpleDataObjects\Tests\Fixtures\UserData; use StdOut\SimpleDataObjects\Tests\Laravel\TestCase; @@ -18,6 +19,7 @@ protected function setUp(): void parent::setUp(); $this->cacheDir = sys_get_temp_dir().'/sdo_provider_test_'.uniqid(); + MetadataRegistry::flush(); } protected function tearDown(): void From 1d909f57eba788a8f92e43c795045d0a93838da5 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:36:41 +0200 Subject: [PATCH 06/10] Make FloatCast reject INF and NAN by default (#34) finite now defaults to true; finite: false keeps accepting non-finite values. Closes #27. --- CHANGELOG.md | 2 ++ docs/casts/numeric.md | 10 +++++----- src/Casts/FloatCast.php | 6 +++--- tests/PrimitiveCastsTest.php | 14 +++++++------- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 907bc59..b298e6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `DataHydrationException` (`tryFrom()` returns `null`, `fromResult()` reports the field) instead of becoming `null`. `#[Cast(new EnumCast(...))]` keeps the old behaviour (#25). +- `FloatCast` rejects `INF` and `NAN` by default (`finite: true`); pass + `finite: false` to accept them (#27). ### Fixed - The `EnumCast` docs named its second argument `fallback`; it is diff --git a/docs/casts/numeric.md b/docs/casts/numeric.md index 97beb7d..897e612 100644 --- a/docs/casts/numeric.md +++ b/docs/casts/numeric.md @@ -41,16 +41,16 @@ class PriceData extends BaseData PriceData::from(['amount' => '9.99'])->amount; // 9.99 (float) ``` -### Rejecting INF and NAN +### INF and NAN -`json_decode('1e400')` yields `INF`, and a float field accepts it — then `toJson()` fails with `JsonException`. Pass `finite: true` to reject non-finite values at hydration: +`json_decode('1e400')` yields `INF`, which `toJson()` cannot encode. `FloatCast` rejects `INF`, `-INF` and `NAN` at hydration with `InvalidArgumentException` (`tryFrom()` returns `null`). Pass `finite: false` to let them through: ```php -#[Cast(new FloatCast(finite: true))] -public readonly float $amount, +#[Cast(new FloatCast(finite: false))] +public readonly float $ratio, ``` -`INF`, `-INF` and `NAN` then throw `InvalidArgumentException`, and `tryFrom()` returns `null`. Without `finite` they pass through unchanged. +Before 3.0 the default was `finite: false`. ## Null Handling diff --git a/src/Casts/FloatCast.php b/src/Casts/FloatCast.php index 697d649..91c8ec6 100644 --- a/src/Casts/FloatCast.php +++ b/src/Casts/FloatCast.php @@ -12,13 +12,13 @@ final class FloatCast implements CastsValue, ProvidesJsonSchema { public function __construct( private readonly int $decimals = -1, - private readonly bool $finite = false, + private readonly bool $finite = true, ) {} /** @param array $state */ public static function __set_state(array $state): self { - return new self($state['decimals'], $state['finite'] ?? false); + return new self($state['decimals'], $state['finite'] ?? true); } public function get(#[\SensitiveParameter] mixed $value): ?float @@ -30,7 +30,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?float $float = (float) $value; if ($this->finite && ! is_finite($float)) { - throw new InvalidArgumentException('FloatCast(finite: true) rejects INF and NAN.'); + throw new InvalidArgumentException('FloatCast rejects INF and NAN; pass finite: false to accept them.'); } return $this->decimals >= 0 ? round($float, $this->decimals) : $float; diff --git a/tests/PrimitiveCastsTest.php b/tests/PrimitiveCastsTest.php index a55f926..41458f2 100644 --- a/tests/PrimitiveCastsTest.php +++ b/tests/PrimitiveCastsTest.php @@ -582,15 +582,15 @@ public function test_comma_separated_cast_rejects_a_non_positive_max_items(): vo new CommaSeparatedCast(maxItems: 0); } - public function test_float_cast_accepts_non_finite_values_by_default(): void + public function test_float_cast_accepts_non_finite_values_when_finite_is_false(): void { - $this->assertSame(INF, (new FloatCast)->get(INF)); - $this->assertNan((new FloatCast)->get(NAN)); + $this->assertSame(INF, (new FloatCast(finite: false))->get(INF)); + $this->assertNan((new FloatCast(finite: false))->get(NAN)); } - public function test_float_cast_finite_rejects_inf_and_nan(): void + public function test_float_cast_rejects_inf_and_nan_by_default(): void { - $cast = new FloatCast(finite: true); + $cast = new FloatCast; $this->assertSame(1.5, $cast->get('1.5')); $this->assertNull($cast->get(null)); @@ -600,14 +600,14 @@ public function test_float_cast_finite_rejects_inf_and_nan(): void $cast->get($value); $this->fail('Expected InvalidArgumentException'); } catch (InvalidArgumentException $e) { - $this->assertSame('FloatCast(finite: true) rejects INF and NAN.', $e->getMessage()); + $this->assertSame('FloatCast rejects INF and NAN; pass finite: false to accept them.', $e->getMessage()); } } } public function test_float_cast_set_state_keeps_finite_and_defaults_it_for_old_caches(): void { - $this->assertEquals(new FloatCast(2, true), FloatCast::__set_state(['decimals' => 2, 'finite' => true])); + $this->assertEquals(new FloatCast(2, false), FloatCast::__set_state(['decimals' => 2, 'finite' => false])); $this->assertEquals(new FloatCast(2), FloatCast::__set_state(['decimals' => 2])); } } From 73b2fc781d5180a1fe4a48894722a0fe6cb58a01 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:42:24 +0200 Subject: [PATCH 07/10] Report cast failures as DataHydrationException (#35) Built-in casts check the input type instead of raising PHP warnings; any exception from a cast, a property pipe or a data collection is rethrown as DataHydrationException naming the field, with the original as the previous exception. Closes #26. --- .claude/skills/migrate-from-v2-to-v3/SKILL.md | 3 +- CHANGELOG.md | 6 + UPGRADE-3.0.md | 13 +- docs/casts/custom.md | 4 + docs/features/hydration.md | 11 ++ src/Casts/BooleanCast.php | 3 +- src/Casts/CommaSeparatedCast.php | 3 +- src/Casts/DateTimeCast.php | 8 +- src/Casts/DateTimeImmutableCast.php | 8 +- src/Casts/FloatCast.php | 4 + src/Casts/IntegerCast.php | 11 +- src/Casts/MoneyCast.php | 2 +- src/Casts/TrimCast.php | 3 +- src/Casts/UuidCast.php | 3 +- src/Exceptions/DataHydrationException.php | 9 +- src/Support/ScalarString.php | 19 +++ src/Support/ValueCaster.php | 44 ++++--- tests/CastFailureTest.php | 121 ++++++++++++++++++ 18 files changed, 239 insertions(+), 36 deletions(-) create mode 100644 src/Support/ScalarString.php create mode 100644 tests/CastFailureTest.php diff --git a/.claude/skills/migrate-from-v2-to-v3/SKILL.md b/.claude/skills/migrate-from-v2-to-v3/SKILL.md index 9de71b9..deb348a 100644 --- a/.claude/skills/migrate-from-v2-to-v3/SKILL.md +++ b/.claude/skills/migrate-from-v2-to-v3/SKILL.md @@ -118,7 +118,8 @@ Where the `try` block calls `from(`, `fromJson(`, `collection(`, `with(` or `fromModel(`, catch `StdOut\SimpleDataObjects\Exceptions\DataHydrationException` instead (cast failures now arrive as that type, with the original as `getPrevious()`), or switch to `tryFrom()` / `fromResult()`. Leave unrelated -catches alone. +catches alone. Tests that assert a cast's exact message from `fromResult()` +now see it prefixed with `Invalid value for field '': `. `FloatCast`: find `new FloatCast` without `finite:`. 3.0 rejects `INF`/`NAN`. Only if a field must store them, add `finite: false` — **STOP AND ASK** first. diff --git a/CHANGELOG.md b/CHANGELOG.md index b298e6f..aeb914d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,12 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. `DataHydrationException` (`tryFrom()` returns `null`, `fromResult()` reports the field) instead of becoming `null`. `#[Cast(new EnumCast(...))]` keeps the old behaviour (#25). +- An exception from a cast, a property pipe or `#[DataCollection]` during + hydration is rethrown as `DataHydrationException` ("Invalid value for + field 'x': ...") with the original as `getPrevious()`. `fromResult()` + reports that message. Built-in casts reject input of the wrong type with + `InvalidArgumentException` instead of PHP warnings or errors; `IntegerCast` + and `FloatCast` reject arrays and objects (#26). - `FloatCast` rejects `INF` and `NAN` by default (`finite: true`); pass `finite: false` to accept them (#27). diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index 1c609b5..cf17f3f 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -121,9 +121,16 @@ before its own exception; `TrimCast`, `BooleanCast`, `DateTimeCast`, `CommaSeparatedCast`, `MoneyCast` and `#[DataCollection]` raised `Error` or `TypeError`. -**3.0:** a cast that cannot handle its input throws -`DataHydrationException` naming the field, with the cast's own exception as -`getPrevious()`. No warnings are emitted. +**3.0:** built-in casts check the input type first (`TrimCast` given an +array throws `InvalidArgumentException: TrimCast expects a string, got +array.`), so no warnings are emitted. Any exception from a cast, a property +pipe or `#[DataCollection]` reaches the caller as `DataHydrationException` +naming the field, with the original as `getPrevious()`: +`Invalid value for field 'id': UuidCast expects a string, got array.` +`fromResult()` reports that message under the field's key. Exceptions that +already are `DataHydrationException` (nested data classes) are unchanged. +`IntegerCast` and `FloatCast` reject arrays and objects, which 2.x turned +into `1`. **What to do:** catch `DataHydrationException` (or use `tryFrom()` / `fromResult()`) where you caught `TypeError`, `Error` or diff --git a/docs/casts/custom.md b/docs/casts/custom.md index 6170993..701c48b 100644 --- a/docs/casts/custom.md +++ b/docs/casts/custom.md @@ -71,6 +71,10 @@ $invoice->total->getAmount(); // '1999' $invoice->toArray()['total']; // 1999 ``` +## Errors + +Throw any exception from `get()` when the value cannot be cast. Hydration wraps it in `DataHydrationException` naming the field (the original stays available as `getPrevious()`), so callers catch one exception type for every field. + ## File Cache Compatibility To participate in the file-based metadata cache, the cast must implement `__set_state()`: diff --git a/docs/features/hydration.md b/docs/features/hydration.md index 841d43d..f87686e 100644 --- a/docs/features/hydration.md +++ b/docs/features/hydration.md @@ -190,6 +190,17 @@ If a required field (non-nullable, no default) is missing, `DataHydrationExcepti UserData::from(['name' => 'Alice']); // throws — 'email' is required ``` +## Values a Cast Cannot Handle + +When a [cast](../attributes/cast.md), a property pipe, a nested data class or a `#[DataCollection]` fails on a field's value, `from()` throws `DataHydrationException` naming the field, with the original exception as `getPrevious()`. Built-in casts check the input type first, so a value of the wrong type never raises a PHP warning: + +```php +OrderData::from(['id' => ['x']]); +// DataHydrationException: Invalid value for field 'id': UuidCast expects a string, got array. +``` + +Errors that are already a `DataHydrationException` (from a nested data class, for example) are thrown unchanged. `tryFrom()` returns `null` and `fromResult()` reports the same message under the field's key. + ## Constructor-less DTOs A constructor isn't required. Plain typed property declarations work the same way — hydrated via direct assignment instead of constructor injection: diff --git a/src/Casts/BooleanCast.php b/src/Casts/BooleanCast.php index 90a2609..87e6c36 100644 --- a/src/Casts/BooleanCast.php +++ b/src/Casts/BooleanCast.php @@ -6,6 +6,7 @@ use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; +use StdOut\SimpleDataObjects\Support\ScalarString; final class BooleanCast implements CastsValue, ProvidesJsonSchema { @@ -27,7 +28,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?bool return $value; } - return in_array(strtolower((string) $value), self::TRUTHY, true); + return in_array(strtolower(\is_string($value) ? $value : ScalarString::of($value, 'BooleanCast')), self::TRUTHY, true); } public function set(#[\SensitiveParameter] mixed $value): ?bool diff --git a/src/Casts/CommaSeparatedCast.php b/src/Casts/CommaSeparatedCast.php index 51a49f9..8c0bb37 100644 --- a/src/Casts/CommaSeparatedCast.php +++ b/src/Casts/CommaSeparatedCast.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; +use StdOut\SimpleDataObjects\Support\ScalarString; final class CommaSeparatedCast implements CastsValue, ProvidesJsonSchema { @@ -37,7 +38,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?array return $this->maxItems === null || count($value) <= $this->maxItems ? $value : $this->tooMany(); } - $str = (string) $value; + $str = \is_string($value) ? $value : ScalarString::of($value, 'CommaSeparatedCast'); if ($str === '') { return []; diff --git a/src/Casts/DateTimeCast.php b/src/Casts/DateTimeCast.php index 01aceb7..22741df 100644 --- a/src/Casts/DateTimeCast.php +++ b/src/Casts/DateTimeCast.php @@ -13,6 +13,7 @@ use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; use StdOut\SimpleDataObjects\Support\Redactor; +use StdOut\SimpleDataObjects\Support\ScalarString; final class DateTimeCast implements CastsValue, ProvidesJsonSchema { @@ -46,14 +47,15 @@ public function get(#[\SensitiveParameter] mixed $value): ?DateTime return DateTime::createFromImmutable($value); } + $value = \is_string($value) ? $value : ScalarString::of($value, 'DateTimeCast'); $tz = $this->resolveTimezone(); if ($this->inputFormat !== null) { - $dt = DateTime::createFromFormat($this->inputFormat, (string) $value, $tz); + $dt = DateTime::createFromFormat($this->inputFormat, $value, $tz); if ($dt === false) { throw new InvalidArgumentException( - 'Cannot parse "'.Redactor::forMessage((string) $value)."\" using format \"{$this->inputFormat}\".", + 'Cannot parse "'.Redactor::forMessage($value)."\" using format \"{$this->inputFormat}\".", ); } @@ -61,7 +63,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?DateTime } try { - return new DateTime((string) $value, $tz); + return new DateTime($value, $tz); } catch (DateMalformedStringException $e) { throw new DateMalformedStringException(Redactor::forMessage($e->getMessage())); } diff --git a/src/Casts/DateTimeImmutableCast.php b/src/Casts/DateTimeImmutableCast.php index add8a5b..42b6e17 100644 --- a/src/Casts/DateTimeImmutableCast.php +++ b/src/Casts/DateTimeImmutableCast.php @@ -13,6 +13,7 @@ use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; use StdOut\SimpleDataObjects\Support\Redactor; +use StdOut\SimpleDataObjects\Support\ScalarString; final class DateTimeImmutableCast implements CastsValue, ProvidesJsonSchema { @@ -46,14 +47,15 @@ public function get(#[\SensitiveParameter] mixed $value): ?DateTimeImmutable return DateTimeImmutable::createFromMutable($value); } + $value = \is_string($value) ? $value : ScalarString::of($value, 'DateTimeImmutableCast'); $tz = $this->resolveTimezone(); if ($this->inputFormat !== null) { - $dt = DateTimeImmutable::createFromFormat($this->inputFormat, (string) $value, $tz); + $dt = DateTimeImmutable::createFromFormat($this->inputFormat, $value, $tz); if ($dt === false) { throw new InvalidArgumentException( - 'Cannot parse "'.Redactor::forMessage((string) $value)."\" using format \"{$this->inputFormat}\".", + 'Cannot parse "'.Redactor::forMessage($value)."\" using format \"{$this->inputFormat}\".", ); } @@ -61,7 +63,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?DateTimeImmutable } try { - return new DateTimeImmutable((string) $value, $tz); + return new DateTimeImmutable($value, $tz); } catch (DateMalformedStringException $e) { throw new DateMalformedStringException(Redactor::forMessage($e->getMessage())); } diff --git a/src/Casts/FloatCast.php b/src/Casts/FloatCast.php index 91c8ec6..e4a8b62 100644 --- a/src/Casts/FloatCast.php +++ b/src/Casts/FloatCast.php @@ -27,6 +27,10 @@ public function get(#[\SensitiveParameter] mixed $value): ?float return null; } + if (\is_array($value) || \is_object($value)) { + throw new InvalidArgumentException('FloatCast expects a scalar, got '.get_debug_type($value).'.'); + } + $float = (float) $value; if ($this->finite && ! is_finite($float)) { diff --git a/src/Casts/IntegerCast.php b/src/Casts/IntegerCast.php index a90d5db..1f7440b 100644 --- a/src/Casts/IntegerCast.php +++ b/src/Casts/IntegerCast.php @@ -4,6 +4,7 @@ namespace StdOut\SimpleDataObjects\Casts; +use InvalidArgumentException; use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; @@ -17,7 +18,15 @@ public static function __set_state(array $state): self public function get(#[\SensitiveParameter] mixed $value): ?int { - return $value === null ? null : (int) $value; + if ($value === null) { + return null; + } + + if (\is_array($value) || \is_object($value)) { + throw new InvalidArgumentException('IntegerCast expects a scalar, got '.get_debug_type($value).'.'); + } + + return (int) $value; } public function set(#[\SensitiveParameter] mixed $value): ?int diff --git a/src/Casts/MoneyCast.php b/src/Casts/MoneyCast.php index 34e9b6a..860483b 100644 --- a/src/Casts/MoneyCast.php +++ b/src/Casts/MoneyCast.php @@ -50,7 +50,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?Money $currency = $value['currency'] ?? $this->currency; $this->assertCurrency($currency); - return new Money($this->resolveAmount($value['amount']), $currency); + return new Money($this->resolveAmount($value['amount'] ?? null), $currency); } return new Money($this->resolveAmount($value), $this->currency); diff --git a/src/Casts/TrimCast.php b/src/Casts/TrimCast.php index daead99..45af28a 100644 --- a/src/Casts/TrimCast.php +++ b/src/Casts/TrimCast.php @@ -6,6 +6,7 @@ use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; +use StdOut\SimpleDataObjects\Support\ScalarString; final class TrimCast implements CastsValue, ProvidesJsonSchema { @@ -29,7 +30,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?string return null; } - $str = trim((string) $value); + $str = trim(\is_string($value) ? $value : ScalarString::of($value, 'TrimCast')); return match ($this->transform) { self::LOWERCASE => strtolower($str), diff --git a/src/Casts/UuidCast.php b/src/Casts/UuidCast.php index f012dfc..dcb2a71 100644 --- a/src/Casts/UuidCast.php +++ b/src/Casts/UuidCast.php @@ -8,6 +8,7 @@ use StdOut\SimpleDataObjects\Contracts\CastsValue; use StdOut\SimpleDataObjects\Contracts\ProvidesJsonSchema; use StdOut\SimpleDataObjects\Support\Redactor; +use StdOut\SimpleDataObjects\Support\ScalarString; final class UuidCast implements CastsValue, ProvidesJsonSchema { @@ -25,7 +26,7 @@ public function get(#[\SensitiveParameter] mixed $value): ?string return null; } - $uuid = (string) $value; + $uuid = \is_string($value) ? $value : ScalarString::of($value, 'UuidCast'); if (! preg_match(self::PATTERN, $uuid)) { throw new InvalidArgumentException('"'.Redactor::forMessage($uuid).'" is not a valid RFC 4122 UUID.'); diff --git a/src/Exceptions/DataHydrationException.php b/src/Exceptions/DataHydrationException.php index 3a861b0..b184137 100644 --- a/src/Exceptions/DataHydrationException.php +++ b/src/Exceptions/DataHydrationException.php @@ -10,9 +10,9 @@ final class DataHydrationException extends RuntimeException { /** @param list $unknownKeys */ - public function __construct(string $message, public readonly array $unknownKeys = []) + public function __construct(string $message, public readonly array $unknownKeys = [], ?\Throwable $previous = null) { - parent::__construct($message); + parent::__construct($message, 0, $previous); } public static function missingField(string $class, string $field): self @@ -58,6 +58,11 @@ public static function unresolvedDiscriminator(string $class, string $field, #[\ return new self("Unknown discriminator value {$given} in field '{$field}' for {$class}."); } + public static function invalidValue(string $field, \Throwable $previous): self + { + return new self("Invalid value for field '{$field}': ".Redactor::forConstructorError($previous), [], $previous); + } + public static function invalidSensitiveValue(string $class, string $field): self { return new self("Invalid value for sensitive field '{$field}' of {$class}."); diff --git a/src/Support/ScalarString.php b/src/Support/ScalarString.php new file mode 100644 index 0000000..7ea8bd2 --- /dev/null +++ b/src/Support/ScalarString.php @@ -0,0 +1,19 @@ +pipes !== []) { - $value = PipelineRunner::runOnValue($value, $meta->phpName, $meta->pipes); - } + try { + if ($meta->pipes !== []) { + $value = PipelineRunner::runOnValue($value, $meta->phpName, $meta->pipes); + } - if ($meta->caster !== null) { - return $meta->caster->get($value); - } + if ($meta->caster !== null) { + return $meta->caster->get($value); + } + + if ($meta->dataCollectionClass !== null) { + if ($value === null) { + return $meta->allowsNull ? null : new TypedDataCollection; + } - if ($meta->dataCollectionClass !== null) { - if ($value === null) { - return $meta->allowsNull ? null : new TypedDataCollection; + return is_iterable($value) + ? $meta->dataCollectionClass::collection($value) + : throw new \InvalidArgumentException('A data collection expects an array, got '.get_debug_type($value).'.'); } - return $meta->dataCollectionClass::collection($value); - } + if ($meta->nestedDataClass !== null && $value !== null) { + return $value instanceof $meta->nestedDataClass ? $value : $meta->nestedDataClass::from($value); + } - if ($meta->nestedDataClass !== null && $value !== null) { - return $value instanceof $meta->nestedDataClass ? $value : $meta->nestedDataClass::from($value); - } + if ($meta->enumClass !== null && $value !== null && ! ($value instanceof UnitEnum)) { + return self::castEnum($meta, $value); + } - if ($meta->enumClass !== null && $value !== null && ! ($value instanceof UnitEnum)) { - return self::castEnum($meta, $value); + return $value; + } catch (DataHydrationException $e) { + throw $e; + } catch (\Throwable $e) { + throw DataHydrationException::invalidValue((string) $meta->inputNames[0], $e); } - - return $value; } public static function castSensitive(ParameterMeta $meta, #[\SensitiveParameter] mixed $value, string $class): mixed diff --git a/tests/CastFailureTest.php b/tests/CastFailureTest.php new file mode 100644 index 0000000..54dbf7c --- /dev/null +++ b/tests/CastFailureTest.php @@ -0,0 +1,121 @@ + */ + public static function wrongTypes(): iterable + { + yield 'BooleanCast' => [new BooleanCast, ['x'], 'BooleanCast expects a string, got array.']; + yield 'CommaSeparatedCast' => [new CommaSeparatedCast, new \stdClass, 'CommaSeparatedCast expects a string, got stdClass.']; + yield 'DateTimeCast' => [new DateTimeCast, ['x'], 'DateTimeCast expects a string, got array.']; + yield 'DateTimeImmutableCast' => [new DateTimeImmutableCast, true, 'DateTimeImmutableCast expects a string, got bool.']; + yield 'TrimCast' => [new TrimCast, ['x'], 'TrimCast expects a string, got array.']; + yield 'UuidCast' => [new UuidCast, ['x'], 'UuidCast expects a string, got array.']; + yield 'IntegerCast' => [new IntegerCast, ['x'], 'IntegerCast expects a scalar, got array.']; + yield 'FloatCast' => [new FloatCast, new \stdClass, 'FloatCast expects a scalar, got stdClass.']; + yield 'MoneyCast without amount' => [new MoneyCast('USD'), ['currency' => 'USD'], 'MoneyCast amount must be an int (minor units) or a numeric decimal string, got null.']; + } + + #[DataProvider('wrongTypes')] + public function test_casts_reject_a_wrong_input_type_without_a_php_error(CastsValue $cast, mixed $value, string $message): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + $cast->get($value); + } + + public function test_string_casts_accept_scalars_and_stringables(): void + { + $value = new class implements \Stringable + { + public function __toString(): string + { + return ' Text '; + } + }; + + $this->assertSame('Text', new TrimCast()->get($value)); + $this->assertSame('12', new TrimCast()->get(12)); + $this->assertSame('1.5', new TrimCast()->get(1.5)); + } + + public function test_cast_failure_is_a_hydration_exception_naming_the_field(): void + { + try { + OrderWithUuidData::from(['id' => ['x']]); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertSame("Invalid value for field 'id': UuidCast expects a string, got array.", $e->getMessage()); + $this->assertInstanceOf(InvalidArgumentException::class, $e->getPrevious()); + } + + $this->assertNull(OrderWithUuidData::tryFrom(['id' => ['x']])); + $this->assertSame(['id' => "Invalid value for field 'id': UuidCast expects a string, got array."], OrderWithUuidData::fromResult(['id' => ['x']])->errors()); + } + + public function test_with_reports_a_cast_failure_the_same_way(): void + { + $order = OrderWithUuidData::from(['id' => '123e4567-e89b-12d3-a456-426614174000']); + + $this->expectException(DataHydrationException::class); + $this->expectExceptionMessage("Invalid value for field 'id'"); + + $order->with(id: 'not-a-uuid'); + } + + public function test_collection_of_a_non_iterable_value_is_rejected_without_internal_paths(): void + { + try { + CollectingEdgeCasesData::from(['required' => ['street' => 's', 'city' => 'c'], 'nullable' => null, 'requiredItems' => 5, 'nullableItems' => null]); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertSame("Invalid value for field 'requiredItems': A data collection expects an array, got int.", $e->getMessage()); + } + } + + public function test_nested_hydration_errors_are_not_wrapped_again(): void + { + try { + CollectingEdgeCasesData::from(['required' => ['street' => 's'], 'nullable' => null, 'requiredItems' => [], 'nullableItems' => null]); + $this->fail('Expected a DataHydrationException.'); + } catch (DataHydrationException $e) { + $this->assertStringStartsWith("Missing required field 'city'", $e->getMessage()); + $this->assertNull($e->getPrevious()); + } + } + + public function test_messages_strip_php_call_sites_and_mask_card_numbers(): void + { + $e = DataHydrationException::invalidValue('card', new \TypeError('Argument #1 must be of type int, string 4111111111111111 given, called in /app/x.php on line 3')); + + $this->assertSame("Invalid value for field 'card': Argument #1 must be of type int, string ************1111 given", $e->getMessage()); + } +} From b0171a88d91399ceb98185fb4414008b9ace2e0d Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:49:34 +0200 Subject: [PATCH 08/10] Reject weak legacy EncryptedCast keys used as the only key (#36) A key given through $key, $env or $provider that is not 32 random bytes throws InvalidArgumentException unless a keyring is configured; next to a keyring it is accepted for reading and stays deprecated. Closes #28. --- CHANGELOG.md | 4 +++ docs/casts/encrypted.md | 6 ++-- docs/features/serialization.md | 2 +- src/Casts/EncryptedCast.php | 6 +++- tests/EncryptedKeyringTest.php | 26 +++++++++++------ tests/EncryptionFormatTest.php | 10 +++---- tests/EqualsDiffTest.php | 2 +- tests/Fixtures/CastableSecretData.php | 2 +- tests/Fixtures/SecretData.php | 2 +- tests/Fixtures/StaticKeyProvider.php | 2 +- tests/MetadataCacheTest.php | 8 +++--- tests/PrimitiveCastsTest.php | 40 +++++++++++++-------------- tests/StackTraceRedactionTest.php | 2 +- 13 files changed, 64 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aeb914d..2ab03d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,10 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. reports that message. Built-in casts reject input of the wrong type with `InvalidArgumentException` instead of PHP warnings or errors; `IntegerCast` and `FloatCast` reject arrays and objects (#26). +- A legacy `EncryptedCast` key (`$key`, `$env`, `$provider`) that is not 32 + random bytes throws `InvalidArgumentException` when it is the only key. + Next to `keyring:` it is accepted to read values written with it and + raises `E_USER_DEPRECATED` (#28). - `FloatCast` rejects `INF` and `NAN` by default (`finite: true`); pass `finite: false` to accept them (#27). diff --git a/docs/casts/encrypted.md b/docs/casts/encrypted.md index cef8aa1..22d208f 100644 --- a/docs/casts/encrypted.md +++ b/docs/casts/encrypted.md @@ -28,7 +28,7 @@ class UserData extends BaseData } ``` -A literal key is also accepted (`new EncryptedCast(key: '...')`) — useful in tests, but **avoid it in application code**: the key would live in your source tree. Exactly one of `key` / `env` / `provider` must be provided; a missing or empty environment variable throws a `RuntimeException` immediately rather than silently encrypting with an empty key. +A literal key is also accepted (`new EncryptedCast(key: '...')`) — useful in tests, but **avoid it in application code**: the key would live in your source tree. Exactly one of `key` / `env` / `provider` must be provided, and its key must be 32 random bytes (raw or base64); a missing or empty environment variable throws a `RuntimeException` immediately rather than silently encrypting with an empty key. ### Key provider (KMS, Vault, HSM) @@ -117,7 +117,7 @@ Every `set()` call produces a **different ciphertext** because a random 24-byte |---|---|---| | Algorithm | XChaCha20-Poly1305-IETF (`sodium_crypto_aead_xchacha20poly1305_ietf_*`) | XSalsa20-Poly1305 (`sodium_crypto_secretbox`) | | Authentication | Poly1305 tag over the ciphertext, the key ID and the class + field binding | Poly1305 tag over the ciphertext only: a valid ciphertext copied to another field or record still decrypts | -| Key | 32 random bytes per key ID; subkey via `sodium_crypto_kdf_derive_from_key` | Any string, hashed with BLAKE2b — a fast hash, not a password KDF | +| Key | 32 random bytes per key ID; subkey via `sodium_crypto_kdf_derive_from_key` | 32 random bytes, hashed with BLAKE2b (a weaker key is accepted only next to `keyring:`, for reading) | | Length | Padded to 32-byte blocks (`sodium_pad`) | Ciphertext length reveals plaintext length | | Nonce | 24 random bytes | 24 random bytes | | Format | `v2::base64url(nonce ‖ ciphertext)` | `base64url(nonce ‖ ciphertext)` | @@ -126,7 +126,7 @@ Both formats are told apart by the `v2:` prefix, which cannot occur in base64url ## Key Handling -Use a key of **32 random bytes** (for example `base64_encode(random_bytes(32))`). The keyring format enforces this. The legacy format hashes any string with a fast function, so a short or guessable key such as a password can be brute-forced from any stored ciphertext. Since 2.9 a legacy key (`$key`, `$env` or `$provider`) that is not 32 random bytes raises an `E_USER_DEPRECATED` notice when the cast is built; 3.0 will reject it. The notice is silenced with `@`, Symfony-style: Laravel still writes it to the `deprecations` log channel, and PHPUnit ignores it unless `ignoreSuppressionOfDeprecations` is set. It never includes the key. +Use a key of **32 random bytes** (for example `base64_encode(random_bytes(32))`). The legacy format hashes its key with a fast function, so a short or guessable key such as a password could be brute-forced from any stored ciphertext. A legacy key (`$key`, `$env` or `$provider`) that is not 32 random bytes therefore throws `InvalidArgumentException` when it is the only key. Next to `keyring:` it is still accepted, only to read values written with it (new values use the keyring), and raises an `E_USER_DEPRECATED` notice until you remove it. The notice is silenced with `@`, Symfony-style: Laravel still writes it to the `deprecations` log channel, and PHPUnit ignores it unless `ignoreSuppressionOfDeprecations` is set. Neither message includes the key. In 2.x a weak legacy key was accepted on its own; see [`UPGRADE-3.0.md`](https://github.com/std-out/simple-data-objects/blob/main/UPGRADE-3.0.md) for moving off one. The cast keeps key material out of the places the library controls: diff --git a/docs/features/serialization.md b/docs/features/serialization.md index 06912c7..e64b178 100644 --- a/docs/features/serialization.md +++ b/docs/features/serialization.md @@ -84,6 +84,6 @@ Casts transform values in both directions. On `toArray()`, the `set()` method of | `DateTimeCast('Y-m-d')` | `DateTime` object | `'2025-06-15'` | | `BooleanCast` | `true` | `true` | | `JsonCast` | `['key' => 'val']` | `'{"key":"val"}'` | -| `EncryptedCast('key')` | plaintext string | XSalsa20-Poly1305 ciphertext | +| `EncryptedCast(keyring: AppKeyring::class)` | plaintext string | XSalsa20-Poly1305 ciphertext | See [Casts →](../casts/index.md) for the full reference. diff --git a/src/Casts/EncryptedCast.php b/src/Casts/EncryptedCast.php index 2ba062f..7acfba6 100644 --- a/src/Casts/EncryptedCast.php +++ b/src/Casts/EncryptedCast.php @@ -76,7 +76,11 @@ public function __construct( } if ($legacyKey !== null && ! KeyMaterial::isRandom($legacyKey)) { - @trigger_error('Since std-out/simple-data-objects 2.9: an EncryptedCast key that is not 32 random bytes (raw or base64-encoded) is deprecated and will be rejected in 3.0. Generate one with base64_encode(random_bytes(32)).', E_USER_DEPRECATED); + if ($keyring === null) { + throw new InvalidArgumentException('An EncryptedCast key must be 32 random bytes (raw or base64-encoded). Generate one with base64_encode(random_bytes(32)), or keep this key next to $keyring to read values encrypted with it.'); + } + + @trigger_error('A weak EncryptedCast $key, $env or $provider key is accepted next to $keyring only to read values encrypted with it. Re-encrypt them (see needsReencryption()) and remove it.', E_USER_DEPRECATED); } $this->secretKey = $legacyKey === null diff --git a/tests/EncryptedKeyringTest.php b/tests/EncryptedKeyringTest.php index 1c712ca..7d4096e 100644 --- a/tests/EncryptedKeyringTest.php +++ b/tests/EncryptedKeyringTest.php @@ -61,18 +61,18 @@ public function test_reads_older_keys_and_writes_with_the_current_one(): void public function test_reads_legacy_ciphertext_when_a_legacy_key_is_configured(): void { - $legacy = (new EncryptedCast('old-key'))->set('secret'); - $cast = new EncryptedCast('old-key', keyring: ConfigurableKeyring::class); + $legacy = (new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->set('secret'); + $cast = new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw=', keyring: ConfigurableKeyring::class); $this->assertSame('secret', $cast->get($legacy)); $this->assertTrue($cast->needsReencryption($legacy)); $this->assertStringStartsWith('v2:k1:', $cast->set('secret')); - $this->assertFalse((new EncryptedCast('old-key'))->needsReencryption($legacy)); + $this->assertFalse((new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->needsReencryption($legacy)); } public function test_legacy_ciphertext_without_a_legacy_key_throws(): void { - $legacy = (new EncryptedCast('old-key'))->set('secret'); + $legacy = (new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->set('secret'); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('legacy format'); @@ -85,7 +85,7 @@ public function test_keyring_ciphertext_without_a_keyring_throws(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessage('no $keyring is configured'); - (new EncryptedCast('old-key'))->get(self::ring()->set('secret')); + (new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->get(self::ring()->set('secret')); } public function test_unknown_key_id_throws(): void @@ -253,7 +253,7 @@ public static function legacyKeys(): iterable } #[DataProvider('legacyKeys')] - public function test_a_legacy_key_that_is_not_32_random_bytes_is_deprecated(string $key, bool $deprecated): void + public function test_a_weak_legacy_key_is_rejected_alone_and_deprecated_next_to_a_keyring(string $key, bool $weak): void { $notices = []; set_error_handler(static function (int $level, string $message) use (&$notices): bool { @@ -263,17 +263,25 @@ public function test_a_legacy_key_that_is_not_32_random_bytes_is_deprecated(stri }); try { - new EncryptedCast($key); new EncryptedCast($key, keyring: ConfigurableKeyring::class); + + try { + new EncryptedCast($key); + $this->assertFalse($weak); + } catch (InvalidArgumentException $e) { + $this->assertTrue($weak); + $this->assertStringContainsString('must be 32 random bytes', $e->getMessage()); + $this->assertStringNotContainsString($key, $e->getMessage()); + } } finally { restore_error_handler(); } - $this->assertCount($deprecated ? 2 : 0, $notices); + $this->assertCount($weak ? 1 : 0, $notices); foreach ($notices as [$level, $message]) { $this->assertSame(E_USER_DEPRECATED, $level); - $this->assertStringContainsString('will be rejected in 3.0', $message); + $this->assertStringContainsString('only to read values encrypted with it', $message); $this->assertStringNotContainsString($key, $message); } } diff --git a/tests/EncryptionFormatTest.php b/tests/EncryptionFormatTest.php index 7e5929e..4973d07 100644 --- a/tests/EncryptionFormatTest.php +++ b/tests/EncryptionFormatTest.php @@ -81,12 +81,12 @@ public function test_explicit_context_is_used_even_when_the_cast_is_unbound(): v public function test_legacy_format_matches_the_documented_construction(): void { - $key = sodium_crypto_generichash('old-key', '', 32); + $key = sodium_crypto_generichash('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw=', '', 32); $nonce = random_bytes(24); $legacy = sodium_bin2base64($nonce.sodium_crypto_secretbox('secret', $nonce, $key), self::BASE64); - $written = sodium_base642bin((new EncryptedCast('old-key'))->set('secret'), self::BASE64); + $written = sodium_base642bin((new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->set('secret'), self::BASE64); - $this->assertSame('secret', (new EncryptedCast('old-key'))->get($legacy)); + $this->assertSame('secret', (new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->get($legacy)); $this->assertSame('secret', sodium_crypto_secretbox_open(substr($written, 24), substr($written, 0, 24), $key)); } @@ -95,7 +95,7 @@ public function test_legacy_value_of_exactly_one_nonce_is_too_short(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Encrypted value is too short.'); - (new EncryptedCast('old-key'))->get(sodium_bin2base64(str_repeat('x', 24), self::BASE64)); + (new EncryptedCast('diwI/BehzF8A0kj4tQ8vL00X/yk0rDHmTerLP1uz8uw='))->get(sodium_bin2base64(str_repeat('x', 24), self::BASE64)); } public function test_payload_containing_a_colon_is_not_valid_base64(): void @@ -135,7 +135,7 @@ public function test_error_messages_name_the_expected_contract(): void foreach ([ static fn () => new EncryptedCast(keyring: \stdClass::class), static fn () => new EncryptedCast(provider: \stdClass::class), - static fn () => (new EncryptedCast('k'))->set([]), + static fn () => (new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='))->set([]), ] as $call) { try { $call(); diff --git a/tests/EqualsDiffTest.php b/tests/EqualsDiffTest.php index 6edc728..5efe806 100644 --- a/tests/EqualsDiffTest.php +++ b/tests/EqualsDiffTest.php @@ -143,7 +143,7 @@ public function test_diff_ignores_reencryption_and_reports_ciphertext_of_changed public function test_plaintext_comparison_mode_is_scoped_and_restored(): void { - $cast = new EncryptedCast('test-encryption-key'); + $cast = new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='); $inner = EncryptedCast::comparingPlaintext(static function () use ($cast): array { $nested = EncryptedCast::comparingPlaintext(static fn (): ?string => $cast->set('x')); diff --git a/tests/Fixtures/CastableSecretData.php b/tests/Fixtures/CastableSecretData.php index 669aff9..2902ae4 100644 --- a/tests/Fixtures/CastableSecretData.php +++ b/tests/Fixtures/CastableSecretData.php @@ -16,7 +16,7 @@ final class CastableSecretData extends BaseData implements Castable public function __construct( public readonly string $label, - #[Cast(new EncryptedCast('test-encryption-key'))] + #[Cast(new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='))] public readonly string $pan, ) {} } diff --git a/tests/Fixtures/SecretData.php b/tests/Fixtures/SecretData.php index 84038b8..359df22 100644 --- a/tests/Fixtures/SecretData.php +++ b/tests/Fixtures/SecretData.php @@ -11,7 +11,7 @@ class SecretData extends BaseData { public function __construct( - #[Cast(new EncryptedCast('test-encryption-key'))] + #[Cast(new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='))] public readonly string $token, ) {} } diff --git a/tests/Fixtures/StaticKeyProvider.php b/tests/Fixtures/StaticKeyProvider.php index ed951b6..c98fdc4 100644 --- a/tests/Fixtures/StaticKeyProvider.php +++ b/tests/Fixtures/StaticKeyProvider.php @@ -10,6 +10,6 @@ final class StaticKeyProvider implements EncryptionKeyProvider { public function key(): string { - return 'provider-key'; + return 's/rAunJu2UVFegODXBdxxfC+RlDT66KL7yeKID87Hrw='; } } diff --git a/tests/MetadataCacheTest.php b/tests/MetadataCacheTest.php index f24da29..716c903 100644 --- a/tests/MetadataCacheTest.php +++ b/tests/MetadataCacheTest.php @@ -206,7 +206,7 @@ public function test_encrypted_cast_is_never_persisted_to_disk(): void { MetadataRegistry::setStoragePath($this->cacheDir); - $cast = new EncryptedCast('test-encryption-key'); + $cast = new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='); $encrypted = $cast->set('secret'); SecretData::from(['token' => $encrypted]); @@ -601,17 +601,17 @@ public function test_encrypted_cast_refuses_serialization(): void { $this->expectException(\LogicException::class); - serialize(new EncryptedCast('direct-test-key')); + serialize(new EncryptedCast('Zwhr+hBsO4FcILE2ijKHQRWYnlFTzjcIkUHnZGuLvVE=')); } public function test_encrypted_cast_redacts_debug_output(): void { ob_start(); - var_dump(new EncryptedCast('direct-test-key')); + var_dump(new EncryptedCast('Zwhr+hBsO4FcILE2ijKHQRWYnlFTzjcIkUHnZGuLvVE=')); $dump = (string) ob_get_clean(); $this->assertStringContainsString('[redacted]', $dump); - $this->assertStringNotContainsString('direct-test-key', $dump); + $this->assertStringNotContainsString('Zwhr+hBsO4FcILE2ijKHQRWYnlFTzjcIkUHnZGuLvVE=', $dump); } public function test_corrupt_cache_files_are_discarded_and_rebuilt(): void diff --git a/tests/PrimitiveCastsTest.php b/tests/PrimitiveCastsTest.php index 41458f2..65098be 100644 --- a/tests/PrimitiveCastsTest.php +++ b/tests/PrimitiveCastsTest.php @@ -198,7 +198,7 @@ public function test_json_cast_hydrates_and_serializes_via_dto(): void public function test_encrypted_cast_round_trip(): void { - $cast = new EncryptedCast('my-key'); + $cast = new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='); $encrypted = $cast->set('secret-token'); $this->assertNotNull($encrypted); @@ -208,14 +208,14 @@ public function test_encrypted_cast_round_trip(): void public function test_encrypted_cast_produces_different_output_each_time(): void { - $cast = new EncryptedCast('my-key'); + $cast = new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='); $this->assertNotSame($cast->set('value'), $cast->set('value')); } public function test_encrypted_cast_null_returns_null(): void { - $cast = new EncryptedCast('my-key'); + $cast = new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='); $this->assertNull($cast->get(null)); $this->assertNull($cast->set(null)); @@ -225,7 +225,7 @@ public function test_encrypted_cast_invalid_base64_throws(): void { $this->expectException(InvalidArgumentException::class); - (new EncryptedCast('my-key'))->get('not!!valid!!base64!!####'); + (new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='))->get('not!!valid!!base64!!####'); } public function test_encrypted_cast_too_short_value_throws(): void @@ -235,12 +235,12 @@ public function test_encrypted_cast_too_short_value_throws(): void // 10 bytes < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (24) $short = sodium_bin2base64(str_repeat('x', 10), SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); - (new EncryptedCast('my-key'))->get($short); + (new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='))->get($short); } public function test_encrypted_cast_tampered_ciphertext_throws(): void { - $cast = new EncryptedCast('my-key'); + $cast = new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='); $encrypted = $cast->set('secret'); $decoded = sodium_base642bin($encrypted, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING); @@ -253,22 +253,22 @@ public function test_encrypted_cast_tampered_ciphertext_throws(): void public function test_encrypted_cast_different_keys_cannot_decrypt(): void { - $encrypted = (new EncryptedCast('key-A'))->set('secret'); + $encrypted = (new EncryptedCast('t5ML2Usu0021nOgH3jcP+ouX/XNgMKXCj+2fb83M0nE='))->set('secret'); $this->expectException(\RuntimeException::class); - (new EncryptedCast('key-B'))->get($encrypted); + (new EncryptedCast('gmK4pRlco+xTd/fXU7T42nSxTsVYVebTpo4zmOF8zXw='))->get($encrypted); } public function test_encrypted_cast_output_is_url_safe_base64(): void { - $encrypted = (new EncryptedCast('my-key'))->set('hello'); + $encrypted = (new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI='))->set('hello'); $this->assertMatchesRegularExpression('/^[A-Za-z0-9_-]+$/', $encrypted); } public function test_encrypted_cast_hydrates_and_decrypts_via_dto(): void { - $cast = new EncryptedCast('test-encryption-key'); + $cast = new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='); $encrypted = $cast->set('my-api-token'); $secret = SecretData::from(['token' => $encrypted]); @@ -278,22 +278,22 @@ public function test_encrypted_cast_hydrates_and_decrypts_via_dto(): void public function test_encrypted_cast_serializes_on_to_array(): void { - $secret = SecretData::from(['token' => (new EncryptedCast('test-encryption-key'))->set('my-api-token')]); + $secret = SecretData::from(['token' => (new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='))->set('my-api-token')]); $array = $secret->toArray(); $this->assertNotSame('my-api-token', $array['token']); - $this->assertSame('my-api-token', (new EncryptedCast('test-encryption-key'))->get($array['token'])); + $this->assertSame('my-api-token', (new EncryptedCast('TU/pBcXXXWPceeZh0Zt76EgWHOl78yIlUaMoRPQZeME='))->get($array['token'])); } public function test_encrypted_cast_resolves_key_from_environment(): void { - $_ENV['SDO_TEST_ENC_KEY'] = 'env-key'; + $_ENV['SDO_TEST_ENC_KEY'] = '6iygaMx2UEIC9V32O3i43921RDiiBnAsJiPRgossE1Y='; try { $encrypted = (new EncryptedCast(env: 'SDO_TEST_ENC_KEY'))->set('secret'); // Same key material as passing the literal key directly - $this->assertSame('secret', (new EncryptedCast('env-key'))->get($encrypted)); + $this->assertSame('secret', (new EncryptedCast('6iygaMx2UEIC9V32O3i43921RDiiBnAsJiPRgossE1Y='))->get($encrypted)); } finally { unset($_ENV['SDO_TEST_ENC_KEY']); } @@ -319,14 +319,14 @@ public function test_encrypted_cast_rejects_more_than_one_key_source(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Provide exactly one of $key, $env or $provider.'); - new EncryptedCast('my-key', provider: StaticKeyProvider::class); + new EncryptedCast('XniGPtH/ufxmsdYWNLEmv46yAmfnmWKX7uubGcjA9zI=', provider: StaticKeyProvider::class); } public function test_encrypted_cast_resolves_key_from_provider(): void { $encrypted = (new EncryptedCast(provider: StaticKeyProvider::class))->set('secret'); - $this->assertSame('secret', (new EncryptedCast('provider-key'))->get($encrypted)); + $this->assertSame('secret', (new EncryptedCast('s/rAunJu2UVFegODXBdxxfC+RlDT66KL7yeKID87Hrw='))->get($encrypted)); } public function test_encrypted_cast_rejects_a_class_that_is_not_a_key_provider(): void @@ -347,8 +347,8 @@ public function test_encrypted_cast_rejects_an_empty_key_from_provider(): void public function test_encrypted_cast_hides_the_derived_key_from_every_dump(): void { - $cast = new EncryptedCast('dump-test-key'); - $key = sodium_crypto_generichash('dump-test-key', '', SODIUM_CRYPTO_SECRETBOX_KEYBYTES); + $cast = new EncryptedCast('adwDDehVBoyyh48+JHnjn6/uCnnVprN2E9+X0oaMrSw='); + $key = sodium_crypto_generichash('adwDDehVBoyyh48+JHnjn6/uCnnVprN2E9+X0oaMrSw=', '', SODIUM_CRYPTO_SECRETBOX_KEYBYTES); $dumps = [var_export($cast, true), print_r((array) $cast, true), (string) json_encode((array) $cast), print_r($cast, true)]; foreach ($dumps as $dump) { @@ -531,12 +531,12 @@ public function test_encrypted_cast_refuses_to_encrypt_an_array(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('got array'); - (new EncryptedCast(key: 'test-key'))->set(['pan' => '4111111111111111']); + (new EncryptedCast(key: 'Yq+HBHZPr46oL8Yc6cTDkItsuX1GOmNOnlh9fIhdsO8='))->set(['pan' => '4111111111111111']); } public function test_encrypted_cast_encrypts_stringable_values(): void { - $cast = new EncryptedCast(key: 'test-key'); + $cast = new EncryptedCast(key: 'Yq+HBHZPr46oL8Yc6cTDkItsuX1GOmNOnlh9fIhdsO8='); $value = new class implements \Stringable { public function __toString(): string diff --git a/tests/StackTraceRedactionTest.php b/tests/StackTraceRedactionTest.php index 13560f4..b239113 100644 --- a/tests/StackTraceRedactionTest.php +++ b/tests/StackTraceRedactionTest.php @@ -62,7 +62,7 @@ public static function failingCalls(): iterable yield 'cast directly' => [static fn () => (new UuidCast)->get($pan)]; yield 'date cast' => [static fn () => (new DateTimeCast)->get($pan)]; yield 'immutable date cast' => [static fn () => (new DateTimeImmutableCast)->get($pan)]; - yield 'encrypted cast' => [static fn () => (new EncryptedCast('k'))->get($pan.'!')]; + 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'])]; From 0dfb1f5ffcea4d6392f428054a31a13f3564325f Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 15:55:47 +0200 Subject: [PATCH 09/10] Coerce scalar properties without loss (#37) 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']); } From 0395ec66c627bd92b4c596a2072c5993088b4596 Mon Sep 17 00:00:00 2001 From: yuriizee Date: Fri, 27 Nov 2026 17:39:40 +0200 Subject: [PATCH 10/10] Prepare 3.0.0 CHANGELOG [3.0.0], branch alias dev-main 3.x-dev, final UPGRADE-3.0, an Upgrading from 2.x docs page linking the migration skill, the docs version switcher for v3/v2/v1 and the Pages build of v2. --- .github/workflows/pages.yml | 22 ++++++++++++++++++---- CHANGELOG.md | 10 ++++++++-- CONTRIBUTING.md | 7 ++----- UPGRADE-3.0.md | 5 ----- composer.json | 2 +- docs/.vitepress/config.mjs | 8 +++++--- docs/guide/upgrading.md | 19 +++++++++++++++++++ 7 files changed, 53 insertions(+), 20 deletions(-) create mode 100644 docs/guide/upgrading.md diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 11321bc..7e0e114 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -2,7 +2,7 @@ name: Deploy VitePress site to Pages on: push: - branches: [main, v1] + branches: [main, v2, v1] workflow_dispatch: @@ -26,6 +26,13 @@ jobs: path: main fetch-depth: 0 + - name: Checkout v2 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: v2 + path: v2 + fetch-depth: 0 + - name: Checkout v1 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: @@ -43,12 +50,18 @@ jobs: - name: Setup Pages uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d - - name: Build main docs (v2.0 — current) + - name: Build main docs (v3 — current) working-directory: main run: | npm ci npm run docs:build + - name: Build v2 docs (v2.x — maintenance) + working-directory: v2 + run: | + npm ci + npm run docs:build + - name: Build v1 docs (v1.x — stable) working-directory: v1 run: | @@ -59,7 +72,8 @@ jobs: run: | mkdir -p site cp -r main/docs/.vitepress/dist/. site/ - mkdir -p site/v1 + mkdir -p site/v2 site/v1 + cp -r v2/docs/.vitepress/dist/. site/v2/ cp -r v1/docs/.vitepress/dist/. site/v1/ - name: Upload artifact @@ -68,7 +82,7 @@ jobs: path: site deploy: - # Every branch pushed above (main, v1) must also be listed in Settings > + # Every branch pushed above (main, v2, v1) must also be listed in Settings > # Environments > github-pages > Deployment branches, or this job 403s. environment: name: github-pages diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4db74..0d59e8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. ## [Unreleased] +## [3.0.0] — 2026-11-27 + +Every change rejects input that 2.x accepted silently or turned into +something else; see [UPGRADE-3.0.md](UPGRADE-3.0.md). + ### Changed (breaking) - The `#[Rules]` of a nested data class, and of the item class of a `#[DataCollection]`, apply when the parent is validated by @@ -53,7 +58,7 @@ and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0. level deep. ### Internal -- The metadata cache format is `sdo-cache-4`; files written by 2.x are +- The metadata cache format is `sdo-cache-5`; files written by 2.x are rebuilt on first use. `ClassMeta` no longer takes `inferRules`. ## [2.9.0] — 2026-11-27 @@ -758,7 +763,8 @@ Initial release. `toResponse()`). - CI pipeline: tests across Laravel 10–13 and a scheduled `composer audit`. -[Unreleased]: https://github.com/std-out/simple-data-objects/compare/v2.9.0...HEAD +[Unreleased]: https://github.com/std-out/simple-data-objects/compare/v3.0.0...HEAD +[3.0.0]: https://github.com/std-out/simple-data-objects/compare/v2.9.0...v3.0.0 [2.9.0]: https://github.com/std-out/simple-data-objects/compare/v2.8.1...v2.9.0 [2.8.1]: https://github.com/std-out/simple-data-objects/compare/v2.8.0...v2.8.1 [2.8.0]: https://github.com/std-out/simple-data-objects/compare/v2.7.0...v2.8.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ae07415..6b2d0f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,11 +88,8 @@ and disclosure. ## Branches -- `main` — the current release line (2.x until 3.0.0 is out). Fixes and - backward-compatible features go here. -- `3.x` — 3.0 in progress. Changes that alter existing behaviour go here - (milestone [3.0.0](https://github.com/std-out/simple-data-objects/milestone/1)); - update `UPGRADE-3.0.md` in the same pull request. +- `main` — the current release line (3.x). Fixes and backward-compatible + features go here. - `v2`, `v1` — maintenance of older major versions. ## Pull request checklist diff --git a/UPGRADE-3.0.md b/UPGRADE-3.0.md index 9a3ae61..bd88869 100644 --- a/UPGRADE-3.0.md +++ b/UPGRADE-3.0.md @@ -1,10 +1,5 @@ # Upgrading from 2.x to 3.0 -> **Work in progress.** 3.0 is being built on the `3.x` branch, one pull -> request per change (milestone [3.0.0](https://github.com/std-out/simple-data-objects/milestone/1)). -> This guide is updated in the same pull request as each change and is final -> only when 3.0.0 is tagged. To try it: `composer require std-out/simple-data-objects:3.0.x-dev`. - 3.0 changes how input is validated and coerced. Every change makes the library reject input that 2.x accepted silently or turned into something else. No public API is removed. Most applications need no code changes, diff --git a/composer.json b/composer.json index 5c38617..b74d458 100644 --- a/composer.json +++ b/composer.json @@ -66,7 +66,7 @@ }, "extra": { "branch-alias": { - "dev-3.x": "3.0.x-dev" + "dev-main": "3.x-dev" } }, "minimum-stability": "stable", diff --git a/docs/.vitepress/config.mjs b/docs/.vitepress/config.mjs index bd98ef1..f15fc6f 100644 --- a/docs/.vitepress/config.mjs +++ b/docs/.vitepress/config.mjs @@ -44,8 +44,9 @@ const guide = [ ], }, { - text: 'Coming from another library', + text: 'Upgrading & migrating', items: [ + { text: 'Upgrading from 2.x', link: '/guide/upgrading' }, { text: 'Migrating from laravel-data', link: '/guide/migrating-from-laravel-data' }, ], }, @@ -194,9 +195,10 @@ export default defineConfig({ }, { text: 'Performance', link: '/guide/performance' }, { - text: 'v2', + text: 'v3', items: [ - { text: 'v2 (current)', link: '/' }, + { text: 'v3 (current)', link: '/' }, + { text: 'v2 (maintenance)', link: 'https://std-out.github.io/simple-data-objects/v2/' }, { text: 'v1 (stable)', link: 'https://std-out.github.io/simple-data-objects/v1/' }, { text: 'Changelog', link: 'https://github.com/std-out/simple-data-objects/blob/main/CHANGELOG.md' }, ], diff --git a/docs/guide/upgrading.md b/docs/guide/upgrading.md new file mode 100644 index 0000000..36b385f --- /dev/null +++ b/docs/guide/upgrading.md @@ -0,0 +1,19 @@ +# Upgrading from 2.x + +3.0 changes how input is validated and coerced. Each change makes the library reject input that 2.x accepted silently or turned into something else. No public API is removed: + +- the `#[Rules]` of nested data classes apply without `#[InferRules]`; +- pipes run before validation; +- `int`, `float`, `string` and `bool` properties take only values that convert without loss; +- an invalid value for a nullable enum property throws; +- cast failures are reported as `DataHydrationException`; +- `FloatCast` rejects `INF` and `NAN` by default; +- a weak legacy `EncryptedCast` key is rejected unless it sits next to a keyring. + +[`UPGRADE-3.0.md`](https://github.com/std-out/simple-data-objects/blob/main/UPGRADE-3.0.md) describes each change, which classes it affects and what to do. + +## With Claude Code + +The repository ships a [`migrate-from-v2-to-v3` skill](https://github.com/std-out/simple-data-objects/blob/main/.claude/skills/migrate-from-v2-to-v3/SKILL.md). Copy it into your project's `.claude/skills/` and ask Claude Code to upgrade simple-data-objects to 3.0. It finds every affected data class, adapts it, stops for decisions that depend on your data, and runs your tests. + +The 2.x documentation stays available at [/v2/](https://std-out.github.io/simple-data-objects/v2/).