Skip to content

Implement ArrayAccess->offsetExists narrowing - #3760

Draft
staabm wants to merge 1 commit into
phpstan:2.3.xfrom
staabm:access
Draft

staabm wants to merge 1 commit into
phpstan:2.3.xfrom
staabm:access

Conversation

@staabm

@staabm staabm commented Dec 29, 2024 •

Copy link
Copy Markdown
Contributor

closes phpstan/phpstan#3323 as described in comment

Comment on lines +69 to +91
foreach($scope->getType($node->var)->getObjectClassReflections() as $classReflection) {
$implementsTags = $classReflection->getImplementsTags();

if (
!isset($implementsTags[\ArrayAccess::class])
|| !$implementsTags[\ArrayAccess::class]->getType() instanceof GenericObjectType
) {
continue;
}

$implementsType = $implementsTags[\ArrayAccess::class]->getType();
$arrayAccessGenericTypes = $implementsType->getTypes();
if (!isset($arrayAccessGenericTypes[1])) {
continue;
}

return $this->typeSpecifier->create(
$node->var,
new HasOffsetValueType($keyType, $arrayAccessGenericTypes[1]),
$context,
$scope,
);
}

@staabm staabm Dec 29, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

reading the "raw" array-access generic type, because ObjectType->getValueType will append null for possibly non-existant offsets. the added null makes it impossible for us to differentiate a nullable-typed generic from a non-nullable generic.

https://3v4l.org/2uhaE


I guess this logic should be moved into the type-system to make it also work for isset() on ArrayAccess objects

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.

Add the sameBehaviour for offsetExists/offsetGet than isset

1 participant