Skip to content

Tie variables destructured from a union of array shapes to each other - #7260

Merged
ondrejmirtes merged 2 commits into
2.3.xfrom
narrow-destructured-shape-union
Nov 30, 2026
Merged

ondrejmirtes merged 2 commits into
2.3.xfrom
narrow-destructured-shape-union

Conversation

@ondrejmirtes

@ondrejmirtes ondrejmirtes commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Destructuring a union of array shapes now ties the destructured variables to each other by the member they came from, so checking the discriminant narrows the other variables:

/** @param array{kind: 'int', payload: int}|array{kind: 'string', payload: string} $message */
['kind' => $kind, 'payload' => $payload] = $message;
if ($kind === 'int') {
	// $payload is int
}
// $payload is string

The same works for positional tuples ([$tag, $value] = $pair) and in reverse (is_int($value) narrows $tag). A variable guards the others only when its types in the members are equal or share no value, so overlapping discriminants narrow nothing. Members and variables are capped by DESTRUCTURED_MEMBERS_LIMIT / DESTRUCTURED_VARIABLES_LIMIT. The native AssignHandler in turbo-ext gets the same change; walk-trace is identical over the default corpus and the full suite passes with and without the extension.

Closes phpstan/phpstan#15893
Closes phpstan/phpstan#12487

Amp thread: https://ampcode.com/threads/T-01a22b9b-2b0a-7521-a915-75eebb3a519c

['kind' => $kind, 'payload' => $payload] = $message reads both variables
from the same member of an array-shape union, so narrowing $kind to one
member's value now narrows $payload to that member's type, and the other way
round. A variable guards the others only when its types in the members are
equal or share no value. The native AssignHandler gets the same change.

Amp-Thread-ID: https://ampcode.com/threads/T-01a22b9b-2b0a-7521-a915-75eebb3a519c
merge() returns array{Type, null}|array{null, Type}, so once $a is null the
destructured $b is a Type. Also regenerates the AssignHandler declarations
for the new helper and adds the issue-bot reproducer of #12487, which the
destructuring narrowing fixes.

Amp-Thread-ID: https://ampcode.com/threads/T-01a22b9b-2b0a-7521-a915-75eebb3a519c
@ondrejmirtes
ondrejmirtes merged commit 217459a into 2.3.x Nov 30, 2026
386 of 397 checks passed
@ondrejmirtes
ondrejmirtes deleted the narrow-destructured-shape-union branch November 30, 2026 09:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant