Skip to content

fix(isset): keep the array value type when an ArrayAccess object is a union alternative - #13118

Merged
orklah merged 17 commits into
vimeo:masterfrom
jirkace:fix/4875-arraylike-union-isset
Nov 22, 2026
Merged

orklah merged 17 commits into
vimeo:masterfrom
jirkace:fix/4875-arraylike-union-isset

Conversation

@jirkace

@jirkace jirkace commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Psalm infers mixed for isset($test['a']) or $test['a'] ?? ... when $test is array<string, string>|ArrayAccess<string, string>, and narrows the array alternative to array{a: mixed}.

Before

/** @var array<string, string>|ArrayAccess<string, string> $test */
$test = $_GET["x"];
if (isset($test["a"])) {
    $a = $test; // ArrayAccess<string, string>|array{a: mixed, ...<string, string>}
}
$b = $test["a"] ?? "a"; // MixedAssignment: mixed|string

After

    $a = $test; // ArrayAccess<string, string>|array{a: string, ...<string, string>}
$b = $test["a"] ?? "a"; // string

Fixes #4875

… union alternative vimeo#4875

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • For a variable whose type is a union of an array and an ArrayAccess object, isset($v[k]) / $v[k] ?? x now narrows the array alternative with the array's own value type (array{a: string, ...<string, string>}) instead of array{a: mixed, ...}, so reads of the result are no longer mixed.
  • When the array alternative's value type is itself mixed, or there is no array alternative, nothing changes (the key stays unknown, as before).
  • Nested keys (isset($v['a']['b'])) narrow the inner array alternative the same way.
  • null|string for $v['a'] ?? 'a' stays: ArrayAccess::offsetGet is declared as returning TValue|null.
  • No existing test expectation was changed; the full self-analysis stays clean.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 7e88954. Configure here.

Comment thread src/Psalm/Type/Reconciler.php Resolved
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: unchanged

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 751 71.5 $\color{gray}{\textsf{+0.6\%}}$ 25 908 53 462 682
✅ symfony 3 600 245.0 $\color{gray}{\textsf{+0.1\%}}$ 50 611 98 405 1 528
✅ doctrine-orm 381 21.4 $\color{gray}{\textsf{-0.4\%}}$ 3 481 6 143 0
✅ psl 617 27.3 $\color{gray}{\textsf{+1.4\%}}$ 1 375 5 615 1
✅ phpunit 455 18.4 $\color{gray}{\textsf{-0.2\%}}$ 1 731 3 410 18
✅ php-parser 226 12.1 $\color{gray}{\textsf{-0.2\%}}$ 17 132 21 025 0
✅ tempest 895 33.8 $\color{gray}{\textsf{+0.7\%}}$ 5 047 10 528 252
✅ amphp-amp 68 1.3 $\color{gray}{\textsf{+1.6\%}}$ 29 49 0
✅ webmozarts-assert 272 2.8 $\color{gray}{\textsf{-1.7\%}}$ 577 2 720 0
✅ guzzle-promises 44 1.0 $\color{gray}{\textsf{-1.9\%}}$ 155 434 2
✅ monolog 135 3.6 $\color{gray}{\textsf{-1.1\%}}$ 913 2 479 10
✅ drupal 4 841 237.1 $\color{gray}{\textsf{-0.4\%}}$ 97 591 169 293 583
Total 13 285 675.4 204 550 373 563 3 076
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +20 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Thresholds apply per project, not to the total.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.

head e7eb769 · base c5f4dfd (merge-base) · workflow run

jirkace and others added 3 commits November 6, 2026 22:07
…union-isset

# Conflicts:
#	tests/ArrayAccessTest.php
…narrowed on an object too vimeo#4875

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	tests/ArrayAccessTest.php
@jirkace

jirkace commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Checked the report's findings on the branch (merged with current master, errorLevel 1), @psalm-trace of the offset inside isset() for array|ArrayAccess unions (master / branch):

code master branch
array<string, array<string, int>>|ArrayAccess<…>, isset($a['x']['y']), trace $a['x'] undefined variable array{y: int, ...<string, int>}
array<string, int>|ArrayAccess<string, int>, isset($a['x']), trace $a['x'] undefined variable undefined variable
array<string, mixed>|ArrayAccess<string, int>, isset($a['x']) undefined variable undefined variable

Finding 1 confirmed in part: for an intermediate segment (first row) the type is computed from the array alternative only (array{y: int, ...}), without the ArrayAccess alternative's own offsetGet type, which is the one the report points at; the final key (rows 2-3) is deliberately unset, as the PR text says, so $a['x'] has no type there on either side. I did not combine the object alternative into the intermediate type.
Not changed: findings 1 (above) and 2 (array<string, mixed>|ArrayAccess keeps the old behaviour on purpose).

Ran: probes on master and on the branch. No code change pushed.

jirkace and others added 3 commits November 15, 2026 14:26
# Conflicts:
#	tests/ArrayAccessTest.php
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…aster dropped null from it vimeo#4875

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@alies-dev alies-dev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixes the reported loss of the array value type at the correct layer (getValueForKey() no longer aborts the whole lookup because one union alternative is an ArrayAccess object); no blocking findings.

Already fixed on master: no. On upstream/master the issue's snippet still traces $test as ArrayAccess<string, string>|array{a: mixed, ...<string, string>} and $b = $test["a"] ?? "a" as mixed|string. With this PR merged into current master the traces are array{a: string, ...} and string.

Overlap / conflicts: tests/ArrayAccessTest.php conflicts with #13087 and #13344 (same insertion spot); trivial. #12633 conflicts textually in Reconciler::getValueForKey(), and the two interact: see my review of #12633 (the continue added here skips the $offset_is_set bookkeeping that PR adds).

Recommendations (non-blocking)

  • tests/ArrayAccessTest.php:1448 (issetOnArrayOrArrayAccessKeepsTheValueTypeOfTheObject) pins int|null|string for $test['a'] inside isset($test['a']). The null cannot be there after isset; it comes from offsetGet(): TValue|null, and it exists because the final key is deliberately dropped from the scope (:621), so a read recomputes from the union (@psalm-trace $test['a'] in the branch is still "undefined variable"). Either record the narrowed final offset (array value type plus the ArrayAccess value without null), or do not pin a known-imprecise result in a test that reads as intended behaviour.
  • The open cursor[bot] comment (flag reuse at Reconciler.php:1194) was written against an earlier commit; the elseif (!$did_type_exist) unset(...) branch now covers it. $has_object_array_access now means "an object alternative was skipped" as well as "abort"; a separate name would avoid the next reader repeating the same worry.

jirkace and others added 2 commits November 18, 2026 10:16
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e of a union with an ArrayAccess

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 5123fee.

CI of the previous head failed in ArrayKeyExistsTest::arrayKeyExistsKeepsAnArrayAccessOfAKnownTypeBeforePhp8 (a case of master): after this PR the array alternative of array<string, int>|ArrayAccess<string, int> inside array_key_exists("k", $a) is array{k: int, ...<string, int>} instead of array{k: mixed, ...<string, int>}. That is the value type this PR keeps, so I changed the expectation of that case to k: int. This is a changed expectation of an existing test. The 7 isset cases of this PR pass.

Run: those cases one by one, phpcs, a full self-analysis (clean). Not run: the whole suite.

…ntermediate offset of an isset path

For `isset($test['a']['b'])` on `array{a?: array{b?: int}}|ArrayAccess<string, array{b?: string}>`
the type of `$test['a']` came from the array alternative only, so `$test['a']['b']` was `int`
although the object can give `string`. An ArrayAccess alternative now contributes the indexable
part of its value type to the intermediate key, and any other object alternative leaves the key
undefined, as before this PR.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

From the triage report generated 2026-11-19 05:16 UTC (reviewed head 5123fee); pushed fbb94f5.

  • Intermediate segment typed from the array alternatives only: confirmed, as already noted on 2026-11-14 and left then. array{a?: array{b?: int}}|ArrayAccess<string, array{b?: string}> with isset($test['a']['b']) gave $test['a']['b'] as int on the previous head (master: mixed|null|string), although the object can give string. For an intermediate segment, an ArrayAccess<K, V> alternative now contributes the indexable part of V (arrays, shapes, objects, mixed; an int cannot be indexed further) and any other object alternative leaves the key undefined, as master does. The review's snippet now gives int|string; issetOnANestedOffsetOfAnArrayOrArrayAccessKeepsTheValueTypeOfTheObject pins it (fails on the previous head with int), and the existing ArrayAccess<string, int> nested case, where the object cannot be indexed further, keeps its int.
  • Only an object typed exactly ArrayAccess<K, V> is read for its value type; a class implementing ArrayAccess with other template parameters leaves the key undefined.

Ran single: the 8 ArrayAccessTest cases of this PR (all pass), self-analysis clean. Not run: the benchmark projects, the full suite (CI).

…e of an intermediate offset, never made it

When no alternative of the base is an array, the intermediate offset of an isset or array_key_exists path
is left as it is, since an object can give a different value on each offsetGet() call (the case
arrayKeyExistsLeavesAnOffsetOfAnArrayAccessAsItIs, which failed after the previous commit). The value type
of an ArrayAccess is only combined with the type that the array alternatives give.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my comment about fbb94f5: that commit broke ArrayKeyExistsTest::arrayKeyExistsLeavesAnOffsetOfAnArrayAccessAsItIs (CI of the head, PHP 8.4/8.6 shard 5: Checked variable $w = array<string, int>|null does not match $w = array{k: int, ...<string, int>}). I had run only the 8 ArrayAccessTest cases of this PR and not that test of the neighbouring file, which I should have said.

Pushed 9c840c6: when no alternative of the base is an array, the intermediate offset is left as it is (an object can give a different value on each offsetGet()); the value type of an ArrayAccess<K, V> is only combined with the type the array alternatives give. Ran single: that case and the 8 ArrayAccessTest cases (all pass), self-analysis clean. Not run: the other ArrayKeyExistsTest cases, the full suite (CI).

# Conflicts:
#	tests/ArrayAccessTest.php

@alies-dev alies-dev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Re-checked against the current head: nothing blocks this anymore, and it is ready to merge. Since the last review, other PRs landed on master and this branch now conflicts in tests/ArrayAccessTest.php (test cases only; #13087 and #13344 add cases at the same spot, so rebasing after them avoids a second round). Please rebase onto master and keep both sides' test cases; I'll merge once CI is green.

@alies-dev alies-dev added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 20, 2026
# Conflicts:
#	tests/ArrayAccessTest.php

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. One regression shows up in the perf report and reproduces locally: when the only other alternative of the object is null or false, the TNull/TFalse branch of getValueForKey() now becomes the offset's type, so the offset is recorded as null. This is the +1 RedundantCondition on Symfony (XliffFileLoader.php:144, $attributes is the ?SimpleXMLElement returned by attributes()):

function f(?SimpleXMLElement $a, bool $b): void {
    if (!(isset($a['r']) || $b)) {
        return;
    }
    echo isset($a['r']) && $a['r'] ? 1 : 0;
    // master: no issue
    // this PR: RedundantCondition: Type null for $a['r'] is always falsy
}

Could you keep the narrowed type only when at least one array alternative (TArray, TKeyedArray, string) contributed to it, and give up as before (return null) otherwise? Please add this snippet as a test case (it must fail on the current head), plus the same shape with SomeObject|false.

The perf report also loses one PossiblyInvalidArrayAccess on Drupal (LocalTaskDefault.php:101, $this->pluginDefinition is array|PluginDefinitionInterface, an object that does not implement ArrayAccess, so the read still fails at runtime). Please check that it comes back with the fix above, or explain why it goes away.

Also, the "After" block of the description says null|string for $b, while issetOnArrayOrArrayAccessKeepsTheArrayValueType asserts string; please align it.

# Conflicts:
#	tests/ArrayAccessTest.php
…lternative gave its type vimeo#4875

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@orklah thanks, addressed in e7eb769:

  • getValueForKey() now keeps the narrowed type of an offset next to an object only when an array alternative (array, a shape, a string) gave it; with only null/false beside the object it gives up as before (return null).
  • An object that isn't known to implement ArrayAccess (PluginDefinitionInterface in Drupal's array|PluginDefinitionInterface) also gives up as before: the PR's new handling is now limited to ArrayAccess objects.

Behaviour change (compared with the previous head)

  • ?SimpleXMLElement / SomeObject|false: no RedundantCondition: Type null for $a['r'] is always falsy any more. New cases ArrayAccessTest::issetOnANullableObjectOffsetKeepsTheOffsetUnknown and issetOnAnObjectOrFalseOffsetKeepsTheOffsetUnknown (your snippet and the SomeObject|false shape); both fail on the previous head with that RedundantCondition and pass now.
  • Corpora at this PR's base (c5f4dfd): drupal and symfony now report exactly what master reports, so LocalTaskDefault.php:101 PossiblyInvalidArrayAccess is back and XliffFileLoader.php:144 RedundantCondition is gone; laravel identical.
  • Description: the "After" block now says $b is string, as issetOnArrayOrArrayAccessKeepsTheArrayValueType asserts (master gives mixed|string, checked).

All cases this PR adds pass one by one; full self-analysis clean (apart from the two local-environment MixedArgument in PoolEventLoopDriverTest). PHPUnit suite not run locally.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jirkace!

@orklah
orklah merged commit 0311f3e into vimeo:master Nov 22, 2026
71 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Could not verify return type when union array<> and arraylike-object<>

3 participants