Skip to content

Add Type::spliceArray(), improve splice_array() array type narrowing #3952

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 2.1.x
Choose a base branch
from

Conversation

herndlm
Copy link
Contributor

@herndlm herndlm commented Apr 19, 2025

Closes phpstan/phpstan#11917

This is very similar to Type:: sliceArray() and it is used in NodeScopeResolver in a similar fashion as Type::popArray() is. Moving logic to Type deals obviously with all accessory types which were not working properly before too like e.g. list or non-empty-array. The only thing I'm slightly worried about is the constant array type handling which is not perfect.

First commit is a tiny refactor I didn't want to cause more noise and dependencies with another PR..

* @var array{a: 0, b: 1, c?: 2} $arr
*/
array_splice($arr, 0, -1, ['hello']);
assertType('array{0: \'hello\', c?: 2}', $arr); // Could be array{0: 'hello', b?: 1, c?: 2}
Copy link
Contributor Author

@herndlm herndlm Apr 19, 2025

Choose a reason for hiding this comment

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

Some types with either negative offsets or negative limits are not optimal but this one is wrong. Not sure what to do here tbh., the handling of those is extremely hard in combination with optional keys. Without optional keys my current approach seems to work fine.

Ideas about this

  • Keep and see if it causes any issues
  • Degrade to general array if negative offsets/limits are involved in combination with optional keys
  • Rewrite and do something semi-crazy with maybe getFiniteTypes() and avoid optional keys completely but have some constant array unions instead

What do you think? Or any other ideas?

@herndlm herndlm force-pushed the array-splice branch 2 times, most recently from 558dec9 to 8425b3c Compare April 19, 2025 19:18
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.

Types are wrong for array_splice
1 participant