Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .claude/skills/migrate-from-v2-to-v3/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
---
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 `<source ignoreSuppressionOfDeprecations="true">` 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: 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
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'` (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).

## 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.
- **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`,
`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
`#[Cast(new EnumCast(Status::class))]`, which maps them to `null` as 2.x did.

## 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. Tests that assert a cast's exact message from `fromResult()`
now see it prefixed with `Invalid value for field '<key>': `.

`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.
22 changes: 18 additions & 4 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Deploy VitePress site to Pages

on:
push:
branches: [main, v1]
branches: [main, v2, v1]

workflow_dispatch:

Expand All @@ -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:
Expand All @@ -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: |
Expand All @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 * * *"

Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 56 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,60 @@ 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
`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).
- 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(...))]`
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).
- 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).

### 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
depth, including self-referential classes, which 2.x validated only one
level deep.

### Internal
- 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

### Fixed
Expand Down Expand Up @@ -709,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
Expand Down
7 changes: 2 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading