Repository navigation
Conversation
…guments allValuesSatisfies() checked the type of an unpacked argument itself instead of its iterable value type. The array type never converts to a non-empty or lowercase string, so sprintf($format, ...$args) lost the accessory types that vsprintf($format, $args) keeps.
|
hey. please see the AI findings I got for your PR:
|
sprintf()with unpacked arguments losesnon-empty-stringandlowercase-string, althoughvsprintf()keeps them for the same list. This PR lets unpacked arguments contribute to these two types, as the values of thevsprintf()array already do.https://phpstan.org/r/bb6ff2df-c0aa-445f-b368-0fda6c8a6e4f
Impact
With
$formatbeingnon-empty-stringand$argsbeingnon-empty-list<non-empty-string>(or thelowercase-stringequivalents):sprintf($format, ...$args)stringnon-empty-stringsprintf($lowerFormat, ...$lowerArgs)stringlowercase-stringvsprintf($format, $args)non-empty-stringThe lowercase check also applies to constant formats. With
$lowerArgsbeinglist<lowercase-string>,sprintf('%s', ...$lowerArgs)changes fromstringtolowercase-string, andsprintf('a%s', ...$lowerArgs)andsprintf('%d', ...$lowerArgs)gainlowercase-stringon top ofnon-falsy-stringandnumeric-string.Cause
SprintfFunctionDynamicReturnTypeExtension::allValuesSatisfies()asks whether every argument converts to a non-empty (or lowercase) string. For an unpacked argument it asked this about the array being unpacked rather than about its values, and an array never satisfies either condition.Fix
For an unpacked argument the check now uses the iterable value type, which is what the
vsprintf()branch of the same method already does.An unpacked list that may be empty is treated like the
vsprintf()case: only its value type is considered. With no values,sprintf()either prints the literal text of the format or throwsArgumentCountError.The check does not inspect the placeholders of the format. A format such as
'%.0s'can still produce an empty string, and'%c'can produce an uppercase letter from a lowercase format and integer arguments. Positionalsprintf()andvsprintf()already infer the narrower type in these cases when the arguments are not constants, and unpackedsprintf()now behaves the same way. This includes the resulting falseidentical.alwaysFalseerrors, for example when comparingsprintf('%c', ...$ints)with'A'.Not covered
Formats that are a single placeholder still do not take the type of an unpacked value.
sprintf('%s', ...$nonFalsyArgs)givesnon-empty-string, notnon-falsy-string, and with an argnum placeholder,sprintf('%2$s', ...$args)staysstring.Testing
Added
tests/PHPStan/Analyser/nsrt/sprintf-unpacked-args.php, covering lists, array shapes,iterableandTraversablevalues, integers, mixes of positional and unpacked arguments, and constant formats. It fails without the source change and passes with it.