Skip to content

Check that array values passed to strtr(), substr_replace(), preg_grep() and similar functions are castable to string - #7150

Merged
staabm merged 3 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-ibcf89h
Nov 25, 2026
Merged

staabm merged 3 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-ibcf89h

Conversation

@phpstan-bot

Copy link
Copy Markdown
Collaborator

Summary

PHP converts each value of the $replace_pairs array of strtr() to a string. Objects that are not Stringable throw an Error, and arrays produce an "Array to string conversion" warning. PHPStan didn't report either case. This PR extends ParameterCastableToStringRule, the rule that already covers array_diff(), natsort(), array_fill_keys() and others, to strtr() and to the sibling functions listed in the issue comments.

Changes

  • src/Rules/Functions/ParameterCastableToStringRule.php:
    • The $checkFirstArgFunctions list is now a function → parameter-indices map.
    • New entries:
      • strtr → $replace_pairs, only for the two-argument form
      • substr_replace → $string, $replace
      • preg_grep → $array
      • preg_replace_callback_array → $subject
      • setlocale → the array $locales form
      • proc_open → array $command, $env_vars
      • pcntl_exec → $args, $env_vars
    • New handling for array_diff_uassoc() / array_intersect_uassoc(): every argument except the trailing comparison callable is checked.
  • The check only fires for arguments that are definitely arrays, so string forms (e.g. strtr($s, 'a', 'b'), setlocale(LC_ALL, 'C')) are unaffected.
  • Not covered: array_multisort() with SORT_STRING depends on the flags, and fits better in SortParameterCastableToStringRule.

Root cause

The function map declares these parameters as plain array (or string|array), and no castable-to-string rule knew about them, so the values were never checked.

Test

tests/PHPStan/Rules/Functions/data/bug-15800.php (in ParameterCastableToStringRuleTest::testBug15800) contains the reproducer from the issue (stdClass and array<int> values for strtr()). It also has positive and negative cases for each newly covered function, including scalar/Stringable values and the three-argument strtr() form, which must not be reported. The test fails without the change.

Fixes phpstan/phpstan#15800

@VincentLanglet VincentLanglet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

How ParameterCastableToStringRule is different than using __stringAndStringable (and similar) in functionMap ?

@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

The reviewer asked a question rather than requesting a change, so I made no code changes and no commits. Below is the answer, based on a side-by-side run. The working tree is clean.

How I compared them: I temporarily changed strtr'1 in resources/functionMap.php to 'replace_pairs'=>'array<__stringAndStringable|int|float|null|bool>' (the vsprintf() pattern) and restored the rule to its pre-PR version. I then ran levels 5, 7 and 9 on the same snippet with each approach, and put everything back afterwards.

Where they behave the same. On direct calls, both report the same calls at the same levels, because both go through RuleLevelHelper:

Value type of $pairs Level 5 Level 7 Level 9
array<string, stdClass> reported reported reported
array<string, stdClass|string> – reported reported
array<string, mixed> – – reported
array<string, Stringable>, array<string, int> (with strict_types) – – –

Both use the identifier argument.type.

Where they differ:

  1. Error message. StringAlwaysAcceptingObjectWithToStringType describes itself as string. So the function map version says:
    Parameter #2 $replace_pairs of function strtr expects array<bool|float|int|string|null>, array<string, stdClass> given.
    That message never mentions Stringable, which is wrong, because Stringable values are accepted. The rule says "expects an array of values castable to string", which matches what PHP actually does.

  2. Callables (the function map wins here). The function map type becomes part of the function's signature. So array_map(strtr(...), ['a'], [$pairs]) with stdClass values is also reported, through the $callback parameter. The rule only looks at FuncCall nodes and misses that case. The side effect is that the narrower type shows up in every closure and callable description of strtr, e.g. Closure(string, array<bool|float|int|string|null>): string.

  3. Checks a static type can't express (the rule wins here). For array_diff_assoc() and array_intersect_assoc(), the rule only checks values whose keys exist in the other arrays (intersectKeyArray()), since only those values get compared. A parameter type in the function map can't depend on the other arguments. That's why these functions live in a rule, and the newly added ones followed the same pattern.

For the functions this PR adds (strtr, substr_replace, preg_grep, preg_replace_callback_array, setlocale'1, proc_open, pcntl_exec, array_*_uassoc), point 3 doesn't apply. Their types could be written in the function map, e.g. string|array<__stringAndStringable|…> for substr_replace or array<…>|null for setlocale'1. In practice the choice comes down to:

  • the clearer message plus the existing rule (current PR), or
  • also catching callable uses, at the cost of a misleading expects array<…string…> message.

I can move these to the function map if the reviewer prefers that. A better option might be to first make __stringAndStringable describe itself as string|Stringable, which fixes the message, and then move them.

@staabm

staabm commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

A better option might be to first make __stringAndStringable describe itself as string|Stringable, which fixes the message, and then move them.

we likely cannot update the type printing because Stringable is php8+ only.

lets go with this rule

@staabm staabm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

will this new errors only be emitted in bleeding edge?

@phpstan-bot

Copy link
Copy Markdown
Collaborator Author

The new errors now appear only with bleeding edge. Before this change they would have shown up in every stable release at level 5. That's committed as 7203cd7 and not pushed.

  • New feature toggle: checkMoreParameterCastableToStringFunctions is declared in conf/parametersSchema.neon and is false in conf/config.neon and true in conf/bleedingEdge.neon. This follows the existing checkParameterCastableToNumberFunctions toggle.
  • Which checks are gated: in ParameterCastableToStringRule, every function this PR adds is gated: strtr, substr_replace, preg_grep, preg_replace_callback_array, setlocale, proc_open, pcntl_exec, array_diff_uassoc and array_intersect_uassoc. Functions the rule already covered (array_diff, natsort, array_fill_keys, etc.) are reported as before, with or without bleeding edge.
  • How the gate works: the gated functions sit in their own list, and the rule returns early for them when the toggle is off. I first tried building the function lists depending on the toggle, but make phpstan reported a false "offset might not exist" error. Keeping the original constant lists plus this separate early return passes cleanly. The downside is that the nine function names appear twice in the file. When the toggle becomes the default, the extra list and the early return can just be deleted.
  • Test: testBug15800 still runs with the toggle on and expects all the new errors. A new test, testBug15800WithoutBleedingEdge, runs the same file with the toggle off and expects no errors.

make tests passes (24000 tests, 117 skipped), make phpstan reports no errors, and make cs is clean.

phpstan-bot and others added 2 commits November 25, 2026 15:23
…g_grep()` and similar functions are castable to string

- ParameterCastableToStringRule: replace the "check first arg" list with a
  function => parameter indices map and add strtr (array form only,
  $replace_pairs), substr_replace ($string, $replace), preg_grep ($array),
  preg_replace_callback_array ($subject), setlocale (array $locales),
  proc_open ($command, $env_vars) and pcntl_exec ($args, $env_vars)
- Check every array argument except the trailing callable of
  array_diff_uassoc() and array_intersect_uassoc()
- Only array arguments are checked, so the string forms (e.g. the
  three-argument strtr()) are unaffected
- array_multisort() with SORT_STRING was left out, it depends on flags
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@staabm
staabm force-pushed the create-pull-request/patch-ibcf89h branch from 7203cd7 to 0b4d5e0 Compare November 25, 2026 14:23
@staabm
staabm merged commit 7fc00a5 into phpstan:2.3.x Nov 25, 2026
89 of 94 checks passed
@staabm
staabm deleted the create-pull-request/patch-ibcf89h branch November 25, 2026 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Check that strtr() replacement values are castable to string

3 participants