From 41ed064335fabba1075ecafd65d2c10c3b52e915 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Wed, 2 Dec 2026 13:00:55 +0000 Subject: [PATCH 1/5] Negate several conditional asserts as a disjunction in the other branch `@phpstan-assert-if-true A $x` together with `@phpstan-assert-if-true B $y` means that a true result says both hold, so a false result says only that at least one of them does not. Each tag used to be negated on its own, narrowing $x to not-A and $y to not-B in the false branch. Several tags are now negated together: about the same expression they combine into one negated tag, about different expressions they narrow nothing. The same goes for several -if-false tags in the true branch. Amp-Thread-ID: https://ampcode.com/threads/T-01a23672-d1c1-7389-8ee4-edae78fcf9ec --- src/PhpDoc/Tag/AssertTag.php | 45 ++++++++ src/Reflection/Assertions.php | 20 ++-- .../nsrt/assert-if-true-conjunction.php | 101 ++++++++++++++++++ turbo-ext/src/Assertions.cpp | 21 ++-- 4 files changed, 168 insertions(+), 19 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/assert-if-true-conjunction.php diff --git a/src/PhpDoc/Tag/AssertTag.php b/src/PhpDoc/Tag/AssertTag.php index cb594db6b93..ca730136690 100644 --- a/src/PhpDoc/Tag/AssertTag.php +++ b/src/PhpDoc/Tag/AssertTag.php @@ -5,6 +5,9 @@ use PHPStan\ShouldNotHappenException; use PHPStan\Turbo\ReferencedByTurboExtension; use PHPStan\Type\Type; +use PHPStan\Type\TypeCombinator; +use function array_map; +use function count; /** @api */ #[ReferencedByTurboExtension(key: 'assertTag')] @@ -85,6 +88,48 @@ public function negate(): self return $tag; } + /** + * What the other branch of a conditional assert says: the tags hold + * together, so when they don't, at least one of them is false. + * `-if-true A $x` with `-if-true B $y` means that a false result says + * $x is not A *or* $y is not B, which narrows neither of them. + * + * @param list $tags + * @return list + */ + public static function negateConjunction(array $tags): array + { + if (count($tags) <= 1) { + return array_map(static fn (self $tag): self => $tag->negate(), $tags); + } + + $subject = $tags[0]->parameter->describe(); + $types = []; + $originalTypes = []; + foreach ($tags as $tag) { + if ($tag->negated !== $tags[0]->negated || $tag->parameter->describe() !== $subject) { + return []; + } + + $types[] = $tag->type; + $originalTypes[] = $tag->getOriginalType(); + } + + // not (A and B) is "not A&B"; not (not A and not B) is "A|B" + if ($tags[0]->negated) { + $type = TypeCombinator::union(...$types); + $originalType = TypeCombinator::union(...$originalTypes); + } else { + $type = TypeCombinator::intersect(...$types); + $originalType = TypeCombinator::intersect(...$originalTypes); + } + + $tag = new self($tags[0]->if, $type, $tags[0]->parameter, !$tags[0]->negated, false, $tags[0]->isExplicit); + $tag->originalType = $originalType; + + return [$tag]; + } + public function isExplicit(): bool { return $this->isExplicit; diff --git a/src/Reflection/Assertions.php b/src/Reflection/Assertions.php index 8d7a5d34724..ec8c1bfd106 100644 --- a/src/Reflection/Assertions.php +++ b/src/Reflection/Assertions.php @@ -23,7 +23,9 @@ * * This class collects all such assertions and provides methods to retrieve them * by condition type. It also handles negation: an `@phpstan-assert-if-true` assertion - * is automatically negated and included in the `getAssertsIfFalse()` result. + * is automatically negated and included in the `getAssertsIfFalse()` result + * (several of them only when they are all about the same expression, see + * AssertTag::negateConjunction()). * * Returned by ExtendedMethodReflection::getAsserts() and FunctionReflection::getAsserts(). * @@ -59,43 +61,43 @@ public function getAsserts(): array } /** - * Includes @phpstan-assert-if-true tags and negated @phpstan-assert-if-false tags. + * Includes @phpstan-assert-if-true tags and the negation of the @phpstan-assert-if-false tags. * * @return AssertTag[] */ public function getAssertsIfTrue(): array { $asserts = []; - $negatedAsserts = []; + $oppositeAsserts = []; foreach ($this->asserts as $assert) { if ($assert->getIf() === AssertTag::IF_TRUE) { $asserts[] = $assert; } elseif ($assert->getIf() === AssertTag::IF_FALSE && !$assert->isEquality()) { - $negatedAsserts[] = $assert->negate(); + $oppositeAsserts[] = $assert; } } - return array_merge($asserts, $negatedAsserts); + return array_merge($asserts, AssertTag::negateConjunction($oppositeAsserts)); } /** - * Includes @phpstan-assert-if-false tags and negated @phpstan-assert-if-true tags. + * Includes @phpstan-assert-if-false tags and the negation of the @phpstan-assert-if-true tags. * * @return AssertTag[] */ public function getAssertsIfFalse(): array { $asserts = []; - $negatedAsserts = []; + $oppositeAsserts = []; foreach ($this->asserts as $assert) { if ($assert->getIf() === AssertTag::IF_FALSE) { $asserts[] = $assert; } elseif ($assert->getIf() === AssertTag::IF_TRUE && !$assert->isEquality()) { - $negatedAsserts[] = $assert->negate(); + $oppositeAsserts[] = $assert; } } - return array_merge($asserts, $negatedAsserts); + return array_merge($asserts, AssertTag::negateConjunction($oppositeAsserts)); } /** @param callable(Type): Type $callable */ diff --git a/tests/PHPStan/Analyser/nsrt/assert-if-true-conjunction.php b/tests/PHPStan/Analyser/nsrt/assert-if-true-conjunction.php new file mode 100644 index 00000000000..07a23eaff76 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/assert-if-true-conjunction.php @@ -0,0 +1,101 @@ += 8.0 + +declare(strict_types = 1); + +namespace AssertIfTrueConjunction; + +use function PHPStan\Testing\assertType; + +final class Sponsor +{ + + public ?string $sponsorName = null; + + public ?string $sponsorUrl = null; + + /** + * @phpstan-assert-if-true !null $this->sponsorName + * @phpstan-assert-if-true !null $this->sponsorUrl + */ + public function isSponsored(): bool + { + return $this->sponsorName !== null && $this->sponsorUrl !== null; + } + + /** + * @phpstan-assert-if-false null $this->sponsorName + * @phpstan-assert-if-false null $this->sponsorUrl + */ + public function isPartiallySponsored(): bool + { + return $this->sponsorName !== null || $this->sponsorUrl !== null; + } + +} + +/** + * @phpstan-assert-if-true !null $value + * @phpstan-assert-if-true !false $value + */ +function isPresent(mixed $value): bool +{ + return $value !== null && $value !== false; +} + +/** + * @phpstan-assert-if-true int $value + * @phpstan-assert-if-true positive-int|string $value + */ +function isPositiveInt(mixed $value): bool +{ + return is_int($value) && $value > 0; +} + +/** + * @phpstan-assert-if-true int $value + * @phpstan-assert-if-true !null $other + */ +function twoParameters(mixed $value, mixed $other): bool +{ + return is_int($value) && $other !== null; +} + +function (Sponsor $sponsor): void { + if ($sponsor->isSponsored()) { + assertType('string', $sponsor->sponsorName); + assertType('string', $sponsor->sponsorUrl); + } else { + assertType('string|null', $sponsor->sponsorName); + assertType('string|null', $sponsor->sponsorUrl); + } + + if ($sponsor->isPartiallySponsored()) { + assertType('string|null', $sponsor->sponsorName); + assertType('string|null', $sponsor->sponsorUrl); + } else { + assertType('null', $sponsor->sponsorName); + assertType('null', $sponsor->sponsorUrl); + } +}; + +function (int|string|false|null $value, ?int $other): void { + if (isPresent($value)) { + assertType('int|string', $value); + } else { + assertType('false|null', $value); + } + + if (isPositiveInt($value)) { + assertType('int<1, max>', $value); + } else { + assertType('int|string|false|null', $value); + } + + if (twoParameters($value, $other)) { + assertType('int', $value); + assertType('int', $other); + } else { + assertType('int|string|false|null', $value); + assertType('int|null', $other); + } +}; diff --git a/turbo-ext/src/Assertions.cpp b/turbo-ext/src/Assertions.cpp index c0ec6442938..e0632b2e42d 100644 --- a/turbo-ext/src/Assertions.cpp +++ b/turbo-ext/src/Assertions.cpp @@ -31,12 +31,12 @@ namespace { pt_method_site pt_as_get_if_site; pt_method_site pt_as_get_type_site; pt_method_site pt_as_with_type_site; -pt_method_site pt_as_negate_site; pt_method_site pt_as_is_equality_site; pt_method_site pt_as_is_negated_site; pt_method_site pt_as_get_parameter_site; pt_method_site pt_as_parameter_describe_site; pt_method_site pt_as_get_assert_tags_site; +pt_method_site pt_as_negate_conjunction_site; zv::Val tagCall(pt_method_site &site, zval *tag, const char *lcname, size_t len, uint32_t argc = 0, zval *argv = NULL) { @@ -139,10 +139,10 @@ class Assertions { zval *asserts = slot(); if (UNEXPECTED(asserts == NULL)) return zv::Val(); - return filterByIf(asserts, "", 0, false, PT_AS_CLOSURE("getAsserts", "58")); + return filterByIf(asserts, "", 0, false, PT_AS_CLOSURE("getAsserts", "60")); } - /* foreach: collect IF_TRUE tags and negated IF_FALSE non-equality tags */ + /* foreach: collect IF_TRUE tags and the negation of the IF_FALSE non-equality tags */ zv::Val getAssertsIfTrue() const { zval *asserts = slot(); @@ -150,7 +150,7 @@ class Assertions return assertsIf(asserts, PT_LC("true"), PT_LC("false")); } - /* foreach: collect IF_FALSE tags and negated IF_TRUE non-equality tags */ + /* foreach: collect IF_FALSE tags and the negation of the IF_TRUE non-equality tags */ zv::Val getAssertsIfFalse() const { zval *asserts = slot(); @@ -168,7 +168,7 @@ class Assertions zv::Arr mapped = zv::Arr::create(zend_hash_num_elements(table)); for (zv::ArrayEntry entry : zv::TableRef(table)) { zval *tag = entry.value().deref().raw(); - if (UNEXPECTED(!requireAssertTag(tag, PT_AS_CLOSURE("mapTypes", "104"), "tag"))) return zv::Val(); + if (UNEXPECTED(!requireAssertTag(tag, PT_AS_CLOSURE("mapTypes", "106"), "tag"))) return zv::Val(); zv::Val type = tagCall(pt_as_get_type_site, tag, PT_LC("gettype")); if (UNEXPECTED(type.isUndef())) return zv::Val(); zv::Val mappedType = pt_type_call_callable(callable, 1, type.raw()); @@ -356,7 +356,7 @@ class Assertions { HashTable *table = Z_ARRVAL_P(asserts); zv::Arr ownTags = zv::Arr::create(0); - zv::Arr negatedTags = zv::Arr::create(0); + zv::Arr oppositeTags = zv::Arr::create(0); for (zv::ArrayEntry entry : zv::TableRef(table)) { zval *tag = entry.value().deref().raw(); if (UNEXPECTED(Z_TYPE_P(tag) != IS_OBJECT)) { @@ -373,12 +373,13 @@ class Assertions bool equality; if (UNEXPECTED(!tagBool(pt_as_is_equality_site, tag, PT_LC("isequality"), equality))) return zv::Val(); if (equality) continue; - zv::Val negatedTag = tagCall(pt_as_negate_site, tag, PT_LC("negate")); - if (UNEXPECTED(negatedTag.isUndef())) return zv::Val(); - negatedTags.push(std::move(negatedTag)); + oppositeTags.push(zv::Ref(tag)); } } - zv::Val negatedValue(std::move(negatedTags)); + /* AssertTag::negateConjunction($oppositeAsserts) */ + zv::Val oppositeValue(std::move(oppositeTags)); + zv::Val negatedValue = pt_call_static_cached(pt_as_negate_conjunction_site, PT_CLASS_ASSERT_TAG, PT_LC("negateconjunction"), 1, oppositeValue.raw()); + if (UNEXPECTED(negatedValue.isUndef())) return zv::Val(); return ptcall::arrayMerge(ownTags.raw(), negatedValue.raw()); } }; From f038fc51a0b873311f4f686dbc278ab95f5fce28 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Wed, 2 Dec 2026 13:00:55 +0000 Subject: [PATCH 2/5] Support @phpstan-assert tags above property hooks, check assert tags of overrides Assert tags written above a property with a get hook (or above the hook itself) narrow their subjects when the property is read, with $this standing for the object the property is fetched from: /** @phpstan-assert-if-true !null $this->sponsorName */ public bool $sponsored { get => $this->sponsorName !== null; } New checks, always on for properties and behind the bleeding edge toggle checkAssertTagsCompatibility for methods and functions: - conditional asserts require a bool return type (property type) - assert tags above a property without a get hook are reported - an overriding method or property has to narrow every expression its parent's tags narrow at least as much, after the call and in each branch it can return. Conditional asserts narrow both branches, so they can't change in either direction. Parameters are matched by position. Amp-Thread-ID: https://ampcode.com/threads/T-01a23672-d1c1-7389-8ee4-edae78fcf9ec --- conf/bleedingEdge.neon | 1 + conf/config.neon | 1 + conf/parametersSchema.neon | 1 + .../Helper/DefaultNarrowingHelper.php | 7 +- .../ExprHandler/PropertyFetchHandler.php | 32 ++- .../Php/PhpClassReflectionExtension.php | 4 + src/Reflection/Php/PhpMethodReflection.php | 44 ++++ src/Rules/Methods/MethodSignatureRule.php | 29 +++ src/Rules/PhpDoc/AssertRuleHelper.php | 51 ++++- src/Rules/PhpDoc/FunctionAssertRule.php | 21 +- src/Rules/PhpDoc/MethodAssertRule.php | 21 +- src/Rules/PhpDoc/OverridingAssertsCheck.php | 168 +++++++++++++++ src/Rules/PhpDoc/PropertyAssertRule.php | 90 ++++++++ .../Properties/OverridingPropertyRule.php | 19 ++ .../Analyser/nsrt/property-hook-asserts.php | 140 +++++++++++++ ...thPossiblyRenamedNamedArgumentRuleTest.php | 3 +- .../Rules/Methods/MethodSignatureRuleTest.php | 44 +++- .../OverridingMethodRuleConfigPhpTest.php | 3 +- .../Methods/OverridingMethodRuleTest.php | 3 +- .../Methods/data/method-assert-override.php | 195 ++++++++++++++++++ .../Rules/PhpDoc/FunctionAssertRuleTest.php | 17 +- .../Rules/PhpDoc/MethodAssertRuleTest.php | 29 ++- .../Rules/PhpDoc/PropertyAssertRuleTest.php | 82 ++++++++ .../data/function-assert-bool-return.php | 15 ++ .../PhpDoc/data/method-assert-bool-return.php | 66 ++++++ .../Rules/PhpDoc/data/property-assert.php | 58 ++++++ .../OverridingPropertyRuleConfigPhpTest.php | 2 + .../Properties/OverridingPropertyRuleTest.php | 29 +++ .../data/property-assert-override.php | 82 ++++++++ turbo-ext/src/DefaultNarrowingHelper.cpp | 6 +- turbo-ext/src/PhpClassReflectionExtension.cpp | 6 + turbo-ext/src/PropertyFetchHandler.cpp | 68 +++++- .../src/generated/DefaultNarrowingHelper.h | 53 ++--- .../src/generated/PropertyFetchHandler.h | 46 +++-- 34 files changed, 1366 insertions(+), 70 deletions(-) create mode 100644 src/Rules/PhpDoc/OverridingAssertsCheck.php create mode 100644 src/Rules/PhpDoc/PropertyAssertRule.php create mode 100644 tests/PHPStan/Analyser/nsrt/property-hook-asserts.php create mode 100644 tests/PHPStan/Rules/Methods/data/method-assert-override.php create mode 100644 tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php create mode 100644 tests/PHPStan/Rules/PhpDoc/data/function-assert-bool-return.php create mode 100644 tests/PHPStan/Rules/PhpDoc/data/method-assert-bool-return.php create mode 100644 tests/PHPStan/Rules/PhpDoc/data/property-assert.php create mode 100644 tests/PHPStan/Rules/Properties/data/property-assert-override.php diff --git a/conf/bleedingEdge.neon b/conf/bleedingEdge.neon index d82b36a0599..867e3def867 100644 --- a/conf/bleedingEdge.neon +++ b/conf/bleedingEdge.neon @@ -39,6 +39,7 @@ parameters: checkMoreParameterCastableToStringFunctions: true checkTemplateTypeBounds: true reportTemplateInImportedTypeAlias: true + checkAssertTagsCompatibility: true checkConditionalParameterTypes: true checkMixedWitnessTypes: true recursiveLoopTypes: true diff --git a/conf/config.neon b/conf/config.neon index 2a9f2e621ae..b324d358020 100644 --- a/conf/config.neon +++ b/conf/config.neon @@ -71,6 +71,7 @@ parameters: checkMoreParameterCastableToStringFunctions: false checkTemplateTypeBounds: false reportTemplateInImportedTypeAlias: false + checkAssertTagsCompatibility: false checkConditionalParameterTypes: false checkMixedWitnessTypes: false recursiveLoopTypes: false diff --git a/conf/parametersSchema.neon b/conf/parametersSchema.neon index eb2014cf8eb..ec4ea5f83e6 100644 --- a/conf/parametersSchema.neon +++ b/conf/parametersSchema.neon @@ -68,6 +68,7 @@ parametersSchema: checkMoreParameterCastableToStringFunctions: bool() checkTemplateTypeBounds: bool() reportTemplateInImportedTypeAlias: bool() + checkAssertTagsCompatibility: bool() checkConditionalParameterTypes: bool() checkMixedWitnessTypes: bool() recursiveLoopTypes: bool() diff --git a/src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php b/src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php index b3e3258a72c..9a5097f0cd6 100644 --- a/src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php +++ b/src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php @@ -857,7 +857,7 @@ public function createIssetSingleSubjectNonTrueTypes( * result-carried structure (impure gate, nullsafe twin) instead of * create()'s scope re-probing. */ - public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike $call, Assertions $assertions, ParametersAcceptor $parametersAcceptor, MutatingScope $scope): ?SpecifiedTypes + public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike|PropertyFetch $call, Assertions $assertions, ParametersAcceptor $parametersAcceptor, MutatingScope $scope): ?SpecifiedTypes { if ($context->null()) { $asserts = $assertions->getAsserts(); @@ -875,7 +875,8 @@ public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike $argsMap = []; $parameters = $parametersAcceptor->getParameters(); - foreach ($call->getArgs() as $i => $arg) { + // a property fetch (its get hook's asserts) has no arguments + foreach ($call instanceof PropertyFetch ? [] : $call->getArgs() as $i => $arg) { if ($arg->unpack) { continue; } @@ -902,7 +903,7 @@ public function specifyTypesFromAsserts(TypeSpecifierContext $context, CallLike $argsMap[$name][] = new TypeExpr($defaultValue); } - if ($call instanceof MethodCall) { + if ($call instanceof MethodCall || $call instanceof PropertyFetch) { $argsMap['this'] = [$call->var]; } diff --git a/src/Analyser/ExprHandler/PropertyFetchHandler.php b/src/Analyser/ExprHandler/PropertyFetchHandler.php index 57dfa2de34f..8cc8460581a 100644 --- a/src/Analyser/ExprHandler/PropertyFetchHandler.php +++ b/src/Analyser/ExprHandler/PropertyFetchHandler.php @@ -24,6 +24,7 @@ use PHPStan\Dependency\Dependencies; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; +use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Rules\Properties\FoundPropertyReflection; use PHPStan\Rules\Properties\PropertyReflectionFinder; use PHPStan\ShouldNotHappenException; @@ -87,6 +88,7 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc $isAlwaysTerminating = $varResult->isAlwaysTerminating(); $scope = $varResult->getScope(); $mayShortCircuit = false; + $getHook = null; if ($expr->name instanceof Identifier) { $supportsPropertyHooks = $scopeBeforeVar->getPhpVersion()->supportsPropertyHooks(); if ($this->checkWholePhpVersionRange ? !$supportsPropertyHooks->no() : $supportsPropertyHooks->yes()) { @@ -94,6 +96,9 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc $propertyHolderType = $varResult->getType(); $propertyReflection = $scopeBeforeVar->getInstancePropertyReflection($propertyHolderType, $propertyName); if ($propertyReflection !== null) { + if ($propertyReflection->hasHook('get')) { + $getHook = $propertyReflection->getHook('get'); + } $propertyDeclaringClass = $propertyReflection->getDeclaringClass(); if ($propertyDeclaringClass->hasNativeProperty($propertyName)) { $nativeProperty = $propertyDeclaringClass->getNativeProperty($propertyName); @@ -196,7 +201,7 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc return new MixedType(); }, - specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted), + specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->specifyTypes($expr, $varResult, $getHook, $context, $beforeScope, $nativeTypesPromoted), ); return $result->withDependencies(Dependencies::merge( $varResult->getDependencies(), @@ -205,6 +210,31 @@ public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetc )); } + /** + * The default narrowing of the fetch, plus the @phpstan-assert tags of the + * property's get hook (written above the property), with $this standing + * for the fetch's receiver - like the asserts of a method call. + */ + private function specifyTypes(PropertyFetch $expr, ExpressionResult $varResult, ?ExtendedMethodReflection $getHook, TypeSpecifierContext $context, MutatingScope $beforeScope, bool $nativeTypesPromoted): SpecifiedTypes + { + $defaultTypes = $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted); + if ($getHook === null || $getHook->getAsserts()->getAll() === []) { + return $defaultTypes; + } + + $scope = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope; + if ($this->defaultNarrowingHelper->callMayHaveBeenSkipped($varResult, $varResult->getTypeOnScope($scope, $nativeTypesPromoted), $context)) { + return $defaultTypes; + } + + $assertTypes = $this->defaultNarrowingHelper->specifyTypesFromAsserts($context, $expr, $getHook->getAsserts(), $getHook->getOnlyVariant(), $scope); + if ($assertTypes === null) { + return $defaultTypes; + } + + return $assertTypes->unionWith($defaultTypes)->setRootExpr($assertTypes->getRootExpr()); + } + /** * The classes of the object the property is fetched from, the class declaring it, and the classes * in its type. diff --git a/src/Reflection/Php/PhpClassReflectionExtension.php b/src/Reflection/Php/PhpClassReflectionExtension.php index e581979d4a6..cdc36897f05 100644 --- a/src/Reflection/Php/PhpClassReflectionExtension.php +++ b/src/Reflection/Php/PhpClassReflectionExtension.php @@ -415,6 +415,10 @@ private function createProperty( $getHook = $getHook->changePropertyGetHookPhpDocType($phpDocType); } } + + if ($resolvedPhpDoc !== null) { + $getHook = $getHook->changePropertyGetHookAsserts($resolvedPhpDoc); + } } if ($betterReflection->hasHook('set')) { diff --git a/src/Reflection/Php/PhpMethodReflection.php b/src/Reflection/Php/PhpMethodReflection.php index f2b79790c9a..e8f34a4cdc9 100644 --- a/src/Reflection/Php/PhpMethodReflection.php +++ b/src/Reflection/Php/PhpMethodReflection.php @@ -547,6 +547,50 @@ public function changePropertySetHookPhpDocType(string $parameterName, Type $php ); } + /** The property's @phpstan-assert tags apply to its get hook unless the hook declares its own. */ + public function changePropertyGetHookAsserts(ResolvedPhpDocBlock $propertyPhpDoc): self + { + if ($this->asserts->getAll() !== []) { + return $this; + } + + $asserts = Assertions::createFromResolvedPhpDocBlock($propertyPhpDoc); + if ($asserts->getAll() === []) { + return $this; + } + + return new self( + $this->initializerExprTypeResolver, + $this->declaringClass, + $this->declaringTrait, + $this->reflection, + $this->reflectionProvider, + $this->attributeReflectionFactory, + $this->allowedConstantsMapProvider, + $this->templateTypeMap, + $this->phpDocParameterTypes, + $this->phpDocReturnType, + $this->phpDocThrowType, + $this->resolvedPhpDocBlock, + $this->deprecatedDescription, + $this->isDeprecated, + $this->isInternal, + $this->isFinal, + $this->isPure, + $asserts, + $this->acceptsNamedArguments, + $this->selfOutType, + $this->phpDocComment, + $this->phpDocParameterOutTypes, + $this->immediatelyInvokedCallableParameters, + $this->phpDocClosureThisTypeParameters, + $this->attributes, + $this->pureUnlessCallableIsImpureParameters, + $this->pureUnlessParameterPassedParameters, + $this->effects, + ); + } + public function getAttributes(): array { return $this->attributes; diff --git a/src/Rules/Methods/MethodSignatureRule.php b/src/Rules/Methods/MethodSignatureRule.php index 48231390e06..dda26eda41b 100644 --- a/src/Rules/Methods/MethodSignatureRule.php +++ b/src/Rules/Methods/MethodSignatureRule.php @@ -12,6 +12,7 @@ use PHPStan\Reflection\ExtendedParameterReflection; use PHPStan\Reflection\ExtendedParametersAcceptor; use PHPStan\Rules\IdentifierRuleError; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleError; use PHPStan\Rules\RuleErrorBuilder; @@ -30,6 +31,7 @@ use PHPStan\Type\TypeTraverser; use PHPStan\Type\VerbosityLevel; use function array_key_exists; +use function array_merge; use function count; use function min; use function sprintf; @@ -51,6 +53,9 @@ public function __construct( private bool $reportStatic, #[AutowiredParameter(ref: '%featureToggles.reportMethodPurityOverride%')] private bool $reportMethodPurityOverride, + private OverridingAssertsCheck $overridingAssertsCheck, + #[AutowiredParameter(ref: '%featureToggles.checkAssertTagsCompatibility%')] + private bool $checkAssertTagsCompatibility, ) { } @@ -115,6 +120,30 @@ public function processNode(Node $node, Scope $scope): array continue; } $parentVariant = $parentVariants[0]; + if ($this->checkAssertTagsCompatibility) { + $parameterNameMapping = ['this' => 'this']; + $parameterTypes = []; + foreach ($parentVariant->getParameters() as $i => $parentParameter) { + $parameterTypes[$parentParameter->getName()] = $parentParameter->getType(); + if (!isset($method->getParameters()[$i])) { + continue; + } + $parameterNameMapping[$parentParameter->getName()] = $method->getParameters()[$i]->getName(); + } + $errors = array_merge($errors, $this->overridingAssertsCheck->check( + $method->getAsserts(), + $method->getReturnType(), + sprintf('method %s::%s()', $declaringClass->getDisplayName(), $method->getName()), + $declaringClass, + $parentMethod->getAsserts(), + sprintf('method %s::%s()', $parentMethodDeclaringClass->getDisplayName(), $parentMethod->getName()), + $parentMethodDeclaringClass, + $parameterNameMapping, + $parameterTypes, + 'it returns', + 'method.childAssertType', + )); + } [$returnTypeCompatibility, $returnType, $parentReturnType] = $this->checkReturnTypeCompatibility($declaringClass, $method, $parentVariant); if ($returnTypeCompatibility->no() || (!$returnTypeCompatibility->yes() && $this->reportMaybes)) { $builder = RuleErrorBuilder::message(sprintf( diff --git a/src/Rules/PhpDoc/AssertRuleHelper.php b/src/Rules/PhpDoc/AssertRuleHelper.php index 550f2cb0722..ebf9945e5eb 100644 --- a/src/Rules/PhpDoc/AssertRuleHelper.php +++ b/src/Rules/PhpDoc/AssertRuleHelper.php @@ -2,13 +2,13 @@ namespace PHPStan\Rules\PhpDoc; -use PhpParser\Node\Stmt\ClassMethod; -use PhpParser\Node\Stmt\Function_; +use PhpParser\Node; use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\AutowiredService; use PHPStan\Node\Expr\TypeExpr; use PHPStan\PhpDoc\Tag\AssertTag; +use PHPStan\Reflection\Assertions; use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Reflection\FunctionReflection; use PHPStan\Reflection\ParametersAcceptor; @@ -21,10 +21,13 @@ use PHPStan\Rules\MissingTypehintCheck; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\ErrorType; +use PHPStan\Type\MixedType; use PHPStan\Type\ObjectType; +use PHPStan\Type\Type; use PHPStan\Type\VerbosityLevel; use function array_key_exists; use function array_merge; +use function array_unique; use function sprintf; use function substr; @@ -51,7 +54,7 @@ public function __construct( */ public function check( Scope $scope, - Function_|ClassMethod $node, + Node $node, ExtendedMethodReflection|FunctionReflection $reflection, ParametersAcceptor $acceptor, ): array @@ -218,4 +221,46 @@ public function check( return $errors; } + /** + * Conditional asserts (-if-true, -if-false) describe what the returned + * bool says about the subjects, so they need a bool return type. + * + * @param string $declaration such as "method Foo::isBar()" + * @param string $typeDescription such as "return type" + * @return list + */ + public function checkConditionalAssertsReturnType(Assertions $asserts, Type $returnType, string $declaration, string $typeDescription): array + { + if ($returnType->isBoolean()->yes()) { + return []; + } + + // no declared type at all + if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) { + return []; + } + + $tagNames = []; + foreach ($asserts->getAll() as $assert) { + if ($assert->getIf() === AssertTag::IF_TRUE) { + $tagNames[] = '@phpstan-assert-if-true'; + } elseif ($assert->getIf() === AssertTag::IF_FALSE) { + $tagNames[] = '@phpstan-assert-if-false'; + } + } + + $errors = []; + foreach (array_unique($tagNames) as $tagName) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'PHPDoc tag %s above %s requires %s bool, %s given.', + $tagName, + $declaration, + $typeDescription, + $returnType->describe(VerbosityLevel::typeOnly()), + ))->identifier('assert.nonBool')->build(); + } + + return $errors; + } + } diff --git a/src/Rules/PhpDoc/FunctionAssertRule.php b/src/Rules/PhpDoc/FunctionAssertRule.php index 83db4414e0d..34f27639752 100644 --- a/src/Rules/PhpDoc/FunctionAssertRule.php +++ b/src/Rules/PhpDoc/FunctionAssertRule.php @@ -4,11 +4,14 @@ use PhpParser\Node; use PHPStan\Analyser\Scope; +use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; use PHPStan\Node\InFunctionNode; use PHPStan\Rules\Rule; +use function array_merge; use function count; +use function sprintf; /** * @implements Rule @@ -18,7 +21,11 @@ final class FunctionAssertRule implements Rule { - public function __construct(private AssertRuleHelper $helper) + public function __construct( + private AssertRuleHelper $helper, + #[AutowiredParameter(ref: '%featureToggles.checkAssertTagsCompatibility%')] + private bool $checkAssertTagsCompatibility, + ) { } @@ -35,7 +42,17 @@ public function processNode(Node $node, Scope $scope): array return []; } - return $this->helper->check($scope, $node->getOriginalNode(), $function, $variants[0]); + $errors = $this->helper->check($scope, $node->getOriginalNode(), $function, $variants[0]); + if (!$this->checkAssertTagsCompatibility) { + return $errors; + } + + return array_merge($errors, $this->helper->checkConditionalAssertsReturnType( + $function->getAsserts(), + $variants[0]->getReturnType(), + sprintf('function %s()', $function->getName()), + 'return type', + )); } } diff --git a/src/Rules/PhpDoc/MethodAssertRule.php b/src/Rules/PhpDoc/MethodAssertRule.php index 45d8eecb28c..c57a471cce1 100644 --- a/src/Rules/PhpDoc/MethodAssertRule.php +++ b/src/Rules/PhpDoc/MethodAssertRule.php @@ -4,11 +4,14 @@ use PhpParser\Node; use PHPStan\Analyser\Scope; +use PHPStan\DependencyInjection\AutowiredParameter; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\DependencyInjection\ValidatesStubFiles; use PHPStan\Node\InClassMethodNode; use PHPStan\Rules\Rule; +use function array_merge; use function count; +use function sprintf; /** * @implements Rule @@ -18,7 +21,11 @@ final class MethodAssertRule implements Rule { - public function __construct(private AssertRuleHelper $helper) + public function __construct( + private AssertRuleHelper $helper, + #[AutowiredParameter(ref: '%featureToggles.checkAssertTagsCompatibility%')] + private bool $checkAssertTagsCompatibility, + ) { } @@ -35,7 +42,17 @@ public function processNode(Node $node, Scope $scope): array return []; } - return $this->helper->check($scope, $node->getOriginalNode(), $method, $variants[0]); + $errors = $this->helper->check($scope, $node->getOriginalNode(), $method, $variants[0]); + if (!$this->checkAssertTagsCompatibility) { + return $errors; + } + + return array_merge($errors, $this->helper->checkConditionalAssertsReturnType( + $method->getAsserts(), + $variants[0]->getReturnType(), + sprintf('method %s::%s()', $method->getDeclaringClass()->getDisplayName(), $method->getName()), + 'return type', + )); } } diff --git a/src/Rules/PhpDoc/OverridingAssertsCheck.php b/src/Rules/PhpDoc/OverridingAssertsCheck.php new file mode 100644 index 00000000000..7f7e75ca6af --- /dev/null +++ b/src/Rules/PhpDoc/OverridingAssertsCheck.php @@ -0,0 +1,168 @@ + $parameterNameMapping parent parameter name => child parameter name, without $ + * @param array $parameterTypes parent parameter name => its type, without $ + * @param string $conditionSubject "it returns" or "it is" + * @param string $identifier such as "method.childAssertType" + * @return list + */ + public function check( + Assertions $asserts, + Type $returnType, + string $description, + ClassReflection $classReflection, + Assertions $parentAsserts, + string $parentDescription, + ClassReflection $parentDeclaringClass, + array $parameterNameMapping, + array $parameterTypes, + string $conditionSubject, + string $identifier, + ): array + { + if ($parentAsserts->getAll() === []) { + return []; + } + + $ancestor = $classReflection->getAncestorWithClassName($parentDeclaringClass->getName()); + if ($ancestor !== null) { + $parentAsserts = $parentAsserts->mapTypes(static fn (Type $type): Type => TemplateTypeHelper::resolveTemplateTypes( + $type, + $ancestor->getActiveTemplateTypeMap(), + $ancestor->getCallSiteVarianceMap(), + TemplateTypeVariance::createInvariant(), + )); + } + + $branches = [ + '' => [$parentAsserts->getAsserts(), $asserts->getAsserts()], + ]; + $returnBoolean = $returnType->toBoolean(); + if (!$returnBoolean->isFalse()->yes()) { + $branches[sprintf(' when %s true', $conditionSubject)] = [$parentAsserts->getAssertsIfTrue(), array_merge($asserts->getAsserts(), $asserts->getAssertsIfTrue())]; + } + if (!$returnBoolean->isTrue()->yes()) { + $branches[sprintf(' when %s false', $conditionSubject)] = [$parentAsserts->getAssertsIfFalse(), array_merge($asserts->getAsserts(), $asserts->getAssertsIfFalse())]; + } + + $errors = []; + foreach ($branches as $branchDescription => [$parentBranchAsserts, $branchAsserts]) { + $parentTypes = []; + foreach ($parentBranchAsserts as $assert) { + $parameterName = substr($assert->getParameter()->getParameterName(), 1); + if (!array_key_exists($parameterName, $parameterNameMapping)) { + continue; + } + + $subject = $assert->getParameter()->changeParameterName('$' . $parameterNameMapping[$parameterName])->describe(); + $parentTypes[$subject] = $this->narrow($parentTypes[$subject] ?? $this->getStartType($subject, $parameterNameMapping, $parameterTypes), $assert); + } + + foreach ($parentTypes as $subject => $parentType) { + $type = null; + foreach ($branchAsserts as $assert) { + if ($assert->getParameter()->describe() !== $subject) { + continue; + } + + $type = $this->narrow($type ?? $this->getStartType($subject, $parameterNameMapping, $parameterTypes), $assert); + } + + if ($type !== null && $parentType->isSuperTypeOf($type)->yes()) { + continue; + } + + if ($type === null) { + $errors[] = RuleErrorBuilder::message(sprintf( + '%s does not narrow %s%s, but overridden %s narrows it to %s.', + ucfirst($description), + $subject, + $branchDescription, + $parentDescription, + $parentType->describe(VerbosityLevel::precise()), + )) + ->identifier($identifier) + ->tip('PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.') + ->build(); + continue; + } + + $errors[] = RuleErrorBuilder::message(sprintf( + '%s narrows %s to %s%s, but overridden %s narrows it to %s.', + ucfirst($description), + $subject, + $type->describe(VerbosityLevel::precise()), + $branchDescription, + $parentDescription, + $parentType->describe(VerbosityLevel::precise()), + ))->identifier($identifier)->build(); + } + } + + return $errors; + } + + /** + * @param array $parameterNameMapping + * @param array $parameterTypes + */ + private function getStartType(string $subject, array $parameterNameMapping, array $parameterTypes): Type + { + foreach ($parameterNameMapping as $parentParameterName => $parameterName) { + if ($subject !== '$' . $parameterName || !array_key_exists($parentParameterName, $parameterTypes)) { + continue; + } + + return TemplateTypeHelper::resolveToBounds($parameterTypes[$parentParameterName]); + } + + return new MixedType(); + } + + private function narrow(Type $type, AssertTag $assert): Type + { + $assertedType = TemplateTypeHelper::resolveToBounds($assert->getType()); + if ($assert->isNegated()) { + return TypeCombinator::remove($type, $assertedType); + } + + return TypeCombinator::intersect($type, $assertedType); + } + +} diff --git a/src/Rules/PhpDoc/PropertyAssertRule.php b/src/Rules/PhpDoc/PropertyAssertRule.php new file mode 100644 index 00000000000..956105692af --- /dev/null +++ b/src/Rules/PhpDoc/PropertyAssertRule.php @@ -0,0 +1,90 @@ + + */ +#[RegisteredRule(level: 2)] +final class PropertyAssertRule implements Rule +{ + + public function __construct( + private AssertRuleHelper $helper, + private FileTypeMapper $fileTypeMapper, + ) + { + } + + public function getNodeType(): string + { + return ClassPropertyNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $classReflection = $node->getClassReflection(); + $propertyReflection = $classReflection->getNativeProperty($node->getName()); + $propertyDescription = sprintf('property %s::$%s', $classReflection->getDisplayName(), $node->getName()); + + if (!$propertyReflection->hasHook('get')) { + $phpDoc = $node->getPhpDoc(); + if ($phpDoc === null) { + return []; + } + + $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc( + $scope->getFile(), + $classReflection->getName(), + $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null, + null, + $phpDoc, + ); + + $tagNames = []; + foreach ($resolvedPhpDoc->getAssertTags() as $assertTag) { + $tagNames[] = [ + AssertTag::NULL => '@phpstan-assert', + AssertTag::IF_TRUE => '@phpstan-assert-if-true', + AssertTag::IF_FALSE => '@phpstan-assert-if-false', + ][$assertTag->getIf()]; + } + + $errors = []; + foreach (array_unique($tagNames) as $tagName) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'PHPDoc tag %s above %s is supported only on properties with a get hook.', + $tagName, + $propertyDescription, + ))->identifier('assert.propertyWithoutGetHook')->build(); + } + + return $errors; + } + + $getHook = $propertyReflection->getHook('get'); + + return array_merge( + $this->helper->check($scope, $node, $getHook, $getHook->getOnlyVariant()), + $this->helper->checkConditionalAssertsReturnType( + $getHook->getAsserts(), + $propertyReflection->getReadableType(), + $propertyDescription, + 'type', + ), + ); + } + +} diff --git a/src/Rules/Properties/OverridingPropertyRule.php b/src/Rules/Properties/OverridingPropertyRule.php index e36cdbf741a..73fbf87c8a0 100644 --- a/src/Rules/Properties/OverridingPropertyRule.php +++ b/src/Rules/Properties/OverridingPropertyRule.php @@ -11,12 +11,14 @@ use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Node\ClassPropertyNode; use PHPStan\Php\PhpVersion; +use PHPStan\Reflection\Assertions; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Reflection\Php\PhpPropertyReflection; use PHPStan\Rules\IdentifierRuleError; use PHPStan\Rules\Methods\MethodParameterComparisonHelper; use PHPStan\Rules\Methods\OverridingMethodCheck; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\VerbosityLevel; @@ -39,6 +41,7 @@ public function __construct( private PhpVersion $phpVersion, private OverridingMethodCheck $overridingMethodCheck, private MethodParameterComparisonHelper $methodParameterComparisonHelper, + private OverridingAssertsCheck $overridingAssertsCheck, #[AutowiredParameter] private bool $checkPhpDocMethodSignatures, #[AutowiredParameter(ref: '%reportMaybesInPropertyPhpDocTypes%')] @@ -360,6 +363,22 @@ private function processPrototype( ->build(); } + if ($this->checkPhpDocMethodSignatures && $prototype->hasHook('get')) { + $errors = array_merge($errors, $this->overridingAssertsCheck->check( + $propertyReflection->hasHook('get') ? $propertyReflection->getHook('get')->getAsserts() : Assertions::createEmpty(), + $propertyReflection->getReadableType(), + sprintf('property %s::$%s', $classReflection->getDisplayName(), $node->getName()), + $classReflection, + $prototype->getHook('get')->getAsserts(), + sprintf('property %s::$%s', $prototype->getDeclaringClass()->getDisplayName(), $node->getName()), + $prototype->getDeclaringClass(), + ['this' => 'this'], + [], + 'it is', + 'property.childAssertType', + )); + } + $typeErrors = []; $nativeType = $node->getNativeType(); if ($prototype->hasNativeType()) { diff --git a/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php b/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php new file mode 100644 index 00000000000..74f8118631d --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php @@ -0,0 +1,140 @@ += 8.4 + +declare(strict_types = 1); + +namespace PropertyHookAsserts; + +use function PHPStan\Testing\assertType; + +final class Sponsor +{ + + public ?string $sponsorName = null; + + public ?string $sponsorUrl = null; + + /** + * @phpstan-assert-if-true !null $this->sponsorName + * @phpstan-assert-if-true !null $this->sponsorUrl + */ + public bool $sponsored { + get => $this->sponsorName !== null && $this->sponsorUrl !== null; + } + + /** @phpstan-assert-if-false null $this->sponsorName */ + public bool $named { + get => $this->sponsorName !== null; + } + + public bool $unnamed { + /** @phpstan-assert-if-true null $this->sponsorName */ + get => $this->sponsorName === null; + } + +} + +interface HasValue +{ + + /** @phpstan-assert-if-true int $this->value */ + public bool $hasValue { get; } + + public ?int $value { get; } + +} + +final class ValueImpl implements HasValue +{ + + public ?int $value = null; + + public bool $hasValue { + get => $this->value !== null; + } + +} + +/** @template T of object */ +class Box +{ + + /** @var T|null */ + public ?object $value = null; + + /** @phpstan-assert-if-true T $this->value */ + public bool $full { + get => $this->value !== null; + } + +} + +/** @extends Box<\stdClass> */ +final class StdClassBox extends Box +{ + +} + +function doFoo(Sponsor $sponsor): void +{ + if ($sponsor->sponsored) { + assertType('string', $sponsor->sponsorName); + assertType('string', $sponsor->sponsorUrl); + } else { + assertType('string|null', $sponsor->sponsorName); + assertType('string|null', $sponsor->sponsorUrl); + } + assertType('string|null', $sponsor->sponsorName); + + if (!$sponsor->sponsored) { + return; + } + assertType('string', $sponsor->sponsorUrl); +} + +function doBar(Sponsor $sponsor): void +{ + if ($sponsor->named) { + assertType('string', $sponsor->sponsorName); + } else { + assertType('null', $sponsor->sponsorName); + } + + if ($sponsor->unnamed) { + assertType('null', $sponsor->sponsorName); + } else { + assertType('string', $sponsor->sponsorName); + } +} + +/** + * @param Box<\DateTimeImmutable> $box + */ +function doBaz(HasValue $hasValue, ValueImpl $valueImpl, Box $box, StdClassBox $stdClassBox): void +{ + if ($hasValue->hasValue) { + assertType('int', $hasValue->value); + } + + if ($valueImpl->hasValue) { + assertType('int', $valueImpl->value); + } + + if ($box->full) { + assertType('DateTimeImmutable', $box->value); + } else { + assertType('null', $box->value); + } + + if ($stdClassBox->full) { + assertType('stdClass', $stdClassBox->value); + } +} + +function doLorem(?Sponsor $sponsor): void +{ + if ($sponsor?->sponsored) { + assertType('string', $sponsor->sponsorName); + } else { + assertType('string|null', $sponsor?->sponsorName); + } +} diff --git a/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php b/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php index a435569dd23..9f30ea5d2d9 100644 --- a/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MethodCallWithPossiblyRenamedNamedArgumentRuleTest.php @@ -8,6 +8,7 @@ use PHPStan\Rules\NonStringableDynamicAccessCheck; use PHPStan\Rules\NullsafeCheck; use PHPStan\Rules\ParameterClosureTypeHelper; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\PhpDoc\UnresolvableTypeHelper; use PHPStan\Rules\Properties\PropertyReflectionFinder; use PHPStan\Rules\Rule; @@ -39,7 +40,7 @@ protected function getRule(): Rule ), new OverridingMethodRule( $phpVersion, - new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, true), + new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, true, new OverridingAssertsCheck(), false), false, new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), diff --git a/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php b/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php index e404c5e8731..a5eb3c909d5 100644 --- a/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php +++ b/tests/PHPStan/Rules/Methods/MethodSignatureRuleTest.php @@ -4,6 +4,7 @@ use PHPStan\Php\PhpVersion; use PHPStan\Reflection\Php\PhpClassReflectionExtension; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; @@ -21,6 +22,8 @@ class MethodSignatureRuleTest extends RuleTestCase private bool $reportMethodPurityOverride = false; + private bool $checkAssertTagsCompatibility = false; + protected function getRule(): Rule { $phpVersion = new PhpVersion(PHP_VERSION_ID); @@ -29,7 +32,7 @@ protected function getRule(): Rule return new OverridingMethodRule( $phpVersion, - new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), $this->reportMaybes, $this->reportStatic, $this->reportMethodPurityOverride), + new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), $this->reportMaybes, $this->reportStatic, $this->reportMethodPurityOverride, new OverridingAssertsCheck(), $this->checkAssertTagsCompatibility), true, new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), @@ -698,4 +701,43 @@ public function testPureUnlessParameterPassedOverride(): void ]); } + #[RequiresPhp('>= 8.0.0')] + public function testAssertTags(): void + { + $this->reportMaybes = true; + $this->reportStatic = true; + $this->checkAssertTagsCompatibility = true; + $this->analyse([__DIR__ . '/data/method-assert-override.php'], [ + [ + 'Method MethodAssertOverride\\Narrower::isInt() narrows $x to mixed~int<1, max> when it returns false, but overridden method MethodAssertOverride\\Foo::isInt() narrows it to mixed~int.', + 98, + ], + [ + 'Method MethodAssertOverride\\Narrower::assertInt() narrows $x to string, but overridden method MethodAssertOverride\\Foo::assertInt() narrows it to int.', + 104, + ], + [ + 'Method MethodAssertOverride\\Narrower::both() does not narrow $y when it returns true, but overridden method MethodAssertOverride\\Foo::both() narrows it to string.', + 109, + 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', + ], + [ + 'Method MethodAssertOverride\\Narrower::isIntOneSided() narrows $x to int|string when it returns true, but overridden method MethodAssertOverride\\Foo::isIntOneSided() narrows it to int.', + 115, + ], + [ + 'Method MethodAssertOverride\\StringChecker::check() narrows $x to mixed~string when it returns false, but overridden method MethodAssertOverride\\GenericChecker::check() narrows it to mixed~int.', + 162, + ], + [ + 'Method MethodAssertOverride\\StringChecker::check() narrows $x to string when it returns true, but overridden method MethodAssertOverride\\GenericChecker::check() narrows it to int.', + 162, + ], + [ + 'Method MethodAssertOverride\\Renamed::assertInt() narrows $value to string, but overridden method MethodAssertOverride\\Foo::assertInt() narrows it to int.', + 182, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php b/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php index 3c80b439609..ce6043d3cc0 100644 --- a/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php +++ b/tests/PHPStan/Rules/Methods/OverridingMethodRuleConfigPhpTest.php @@ -4,6 +4,7 @@ use PHPStan\Php\PhpVersion; use PHPStan\Reflection\Php\PhpClassReflectionExtension; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\RequiresPhp; @@ -21,7 +22,7 @@ protected function getRule(): Rule return new OverridingMethodRule( $phpVersion, - new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, false), + new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, false, new OverridingAssertsCheck(), false), false, new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), diff --git a/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php b/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php index 04968069694..ee4be13f5be 100644 --- a/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php +++ b/tests/PHPStan/Rules/Methods/OverridingMethodRuleTest.php @@ -4,6 +4,7 @@ use PHPStan\Php\PhpVersion; use PHPStan\Reflection\Php\PhpClassReflectionExtension; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -30,7 +31,7 @@ protected function getRule(): Rule return new OverridingMethodRule( $phpVersion, - new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, false), + new MethodSignatureRule(new ParentMethodHelper($phpClassReflectionExtension), true, true, false, new OverridingAssertsCheck(), false), false, new MethodParameterComparisonHelper($phpVersion), new MethodVisibilityComparisonHelper(), diff --git a/tests/PHPStan/Rules/Methods/data/method-assert-override.php b/tests/PHPStan/Rules/Methods/data/method-assert-override.php new file mode 100644 index 00000000000..f492134f71f --- /dev/null +++ b/tests/PHPStan/Rules/Methods/data/method-assert-override.php @@ -0,0 +1,195 @@ += 8.0 + +namespace MethodAssertOverride; + +class Foo +{ + + /** @phpstan-assert-if-true int $x */ + public function isInt(mixed $x): bool + { + return is_int($x); + } + + /** @phpstan-assert int $x */ + public function assertInt(mixed $x): void + { + } + + /** + * @phpstan-assert-if-true int $x + * @phpstan-assert-if-true string $y + */ + public function both(mixed $x, mixed $y): bool + { + return is_int($x) && is_string($y); + } + + /** @phpstan-assert-if-true =int $x */ + public function isIntOneSided(mixed $x): bool + { + return is_int($x); + } + + /** @phpstan-assert-if-true int $x */ + public function isIntOnUnion(int|string $x): bool + { + return is_int($x); + } + +} + +class Inherits extends Foo +{ + + public function isInt(mixed $x): bool + { + return false; + } + + public function assertInt(mixed $x): void + { + } + +} + +class SameTags extends Foo +{ + + /** @phpstan-assert-if-true int $renamed */ + public function isInt(mixed $renamed): bool + { + return is_int($renamed); + } + + /** @phpstan-assert positive-int $x */ + public function assertInt(mixed $x): void + { + } + + /** + * @phpstan-assert-if-true int $x + * @phpstan-assert-if-true string $y + * @phpstan-assert-if-true string $z + */ + public function both(mixed $x, mixed $y, mixed $z = null): bool + { + return is_int($x) && is_string($y); + } + + /** @phpstan-assert-if-true =positive-int $x */ + public function isIntOneSided(mixed $x): bool + { + return is_int($x); + } + + /** @phpstan-assert-if-false string $x */ + public function isIntOnUnion(int|string $x): bool + { + return is_int($x); + } + +} + +class Narrower extends Foo +{ + + /** @phpstan-assert-if-true positive-int $x */ + public function isInt(mixed $x): bool + { + return is_int($x) && $x > 0; + } + + /** @phpstan-assert string $x */ + public function assertInt(mixed $x): void + { + } + + /** @phpstan-assert-if-true int $x */ + public function both(mixed $x, mixed $y): bool + { + return is_int($x); + } + + /** @phpstan-assert-if-true =int|string $x */ + public function isIntOneSided(mixed $x): bool + { + return is_int($x) || is_string($x); + } + +} + +class AlwaysTrue extends Foo +{ + + /** + * @phpstan-assert-if-true positive-int $x + * @return true + */ + public function isInt(mixed $x): bool + { + return true; + } + +} + +/** @template T */ +abstract class GenericChecker +{ + + /** @phpstan-assert-if-true T $x */ + abstract public function check(mixed $x): bool; + +} + +/** @extends GenericChecker */ +class IntChecker extends GenericChecker +{ + + /** @phpstan-assert-if-true int $x */ + public function check(mixed $x): bool + { + return is_int($x); + } + +} + +/** @extends GenericChecker */ +class StringChecker extends GenericChecker +{ + + /** @phpstan-assert-if-true string $x */ + public function check(mixed $x): bool + { + return is_string($x); + } + +} + +class Renamed extends Foo +{ + + /** + * @no-named-arguments + * @phpstan-assert-if-true int $value + */ + public function isInt(mixed $value): bool + { + return is_int($value); + } + + /** @phpstan-assert string $value */ + public function assertInt(mixed $value): void + { + } + + /** + * @phpstan-assert-if-true int $y + * @phpstan-assert-if-true string $x + */ + public function both(mixed $y, mixed $x): bool + { + return is_int($y) && is_string($x); + } + +} diff --git a/tests/PHPStan/Rules/PhpDoc/FunctionAssertRuleTest.php b/tests/PHPStan/Rules/PhpDoc/FunctionAssertRuleTest.php index 349175cf336..4a57455f503 100644 --- a/tests/PHPStan/Rules/PhpDoc/FunctionAssertRuleTest.php +++ b/tests/PHPStan/Rules/PhpDoc/FunctionAssertRuleTest.php @@ -11,6 +11,7 @@ use PHPStan\Rules\RestrictedUsage\RestrictedClassNameUsageExtension; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use PHPUnit\Framework\Attributes\RequiresPhp; /** * @extends RuleTestCase @@ -18,6 +19,8 @@ class FunctionAssertRuleTest extends RuleTestCase { + private bool $checkAssertTagsCompatibility = false; + protected function getRule(): Rule { $reflectionProvider = self::createReflectionProvider(); @@ -35,7 +38,7 @@ protected function getRule(): Rule new GenericObjectTypeCheck(), true, true, - )); + ), $this->checkAssertTagsCompatibility); } public function testRule(): void @@ -82,4 +85,16 @@ public function testRule(): void ]); } + #[RequiresPhp('>= 8.0.0')] + public function testBoolReturnType(): void + { + $this->checkAssertTagsCompatibility = true; + $this->analyse([__DIR__ . '/data/function-assert-bool-return.php'], [ + [ + 'PHPDoc tag @phpstan-assert-if-true above function FunctionAssertBoolReturn\\returnsInt() requires return type bool, int given.', + 12, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/PhpDoc/MethodAssertRuleTest.php b/tests/PHPStan/Rules/PhpDoc/MethodAssertRuleTest.php index e8e2abe2bef..8270fe5e588 100644 --- a/tests/PHPStan/Rules/PhpDoc/MethodAssertRuleTest.php +++ b/tests/PHPStan/Rules/PhpDoc/MethodAssertRuleTest.php @@ -11,6 +11,7 @@ use PHPStan\Rules\RestrictedUsage\RestrictedClassNameUsageExtension; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; +use PHPUnit\Framework\Attributes\RequiresPhp; /** * @extends RuleTestCase @@ -18,6 +19,8 @@ class MethodAssertRuleTest extends RuleTestCase { + private bool $checkAssertTagsCompatibility = false; + protected function getRule(): Rule { $reflectionProvider = self::createReflectionProvider(); @@ -35,7 +38,7 @@ protected function getRule(): Rule new GenericObjectTypeCheck(), true, true, - )); + ), $this->checkAssertTagsCompatibility); } public function testRule(): void @@ -163,4 +166,28 @@ public function testBugIncompatibleAssertTypeWithMethodReturnType(): void ]); } + #[RequiresPhp('>= 8.0.0')] + public function testBoolReturnType(): void + { + $this->checkAssertTagsCompatibility = true; + $this->analyse([__DIR__ . '/data/method-assert-bool-return.php'], [ + [ + 'PHPDoc tag @phpstan-assert-if-true above method MethodAssertBoolReturn\\Foo::returnsString() requires return type bool, string given.', + 39, + ], + [ + 'PHPDoc tag @phpstan-assert-if-false above method MethodAssertBoolReturn\\Foo::returnsVoid() requires return type bool, void given.', + 45, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above method MethodAssertBoolReturn\\Foo::returnsNullableBool() requires return type bool, bool|null given.', + 50, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above method MethodAssertBoolReturn\\Foo::returnsMixed() requires return type bool, mixed given.', + 56, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php b/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php new file mode 100644 index 00000000000..923b4b97a0b --- /dev/null +++ b/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php @@ -0,0 +1,82 @@ + + */ +class PropertyAssertRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + $reflectionProvider = self::createReflectionProvider(); + $container = self::getContainer(); + return new PropertyAssertRule(new AssertRuleHelper( + $reflectionProvider, + new UnresolvableTypeHelper(), + new ClassNameCheck( + new ClassCaseSensitivityCheck($reflectionProvider, true, true), + new ClassForbiddenNameCheck($container->getExtensionsCollection(ForbiddenClassNameExtension::class)), + $reflectionProvider, + $container->getExtensionsCollection(RestrictedClassNameUsageExtension::class), + ), + new MissingTypehintCheck(true, [], true), + new GenericObjectTypeCheck(), + true, + true, + ), $container->getByType(FileTypeMapper::class)); + } + + #[RequiresPhp('>= 8.4.0')] + public function testRule(): void + { + $this->analyse([__DIR__ . '/data/property-assert.php'], [ + [ + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$nonBool requires type bool, string given.', + 23, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', + 31, + ], + [ + 'PHPDoc tag @phpstan-assert-if-false above property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', + 31, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$plain is supported only on properties with a get hook.', + 36, + ], + [ + 'Assert references unknown $this->unknown.', + 39, + ], + [ + 'Assert references unknown parameter $name.', + 44, + ], + [ + 'Asserted type string|null for $this->name with type string|null does not narrow down the type.', + 49, + ], + [ + 'Asserted type int for $this->name with type string|null can never happen.', + 53, + ], + ]); + } + +} diff --git a/tests/PHPStan/Rules/PhpDoc/data/function-assert-bool-return.php b/tests/PHPStan/Rules/PhpDoc/data/function-assert-bool-return.php new file mode 100644 index 00000000000..25c92262921 --- /dev/null +++ b/tests/PHPStan/Rules/PhpDoc/data/function-assert-bool-return.php @@ -0,0 +1,15 @@ += 8.0 + +namespace FunctionAssertBoolReturn; + +/** @phpstan-assert-if-true int $x */ +function isInt(mixed $x): bool +{ + return is_int($x); +} + +/** @phpstan-assert-if-true int $x */ +function returnsInt(mixed $x): int +{ + return 1; +} diff --git a/tests/PHPStan/Rules/PhpDoc/data/method-assert-bool-return.php b/tests/PHPStan/Rules/PhpDoc/data/method-assert-bool-return.php new file mode 100644 index 00000000000..9980c6120e8 --- /dev/null +++ b/tests/PHPStan/Rules/PhpDoc/data/method-assert-bool-return.php @@ -0,0 +1,66 @@ += 8.0 + +namespace MethodAssertBoolReturn; + +class Foo +{ + + /** @phpstan-assert-if-true int $x */ + public function isInt(mixed $x): bool + { + return is_int($x); + } + + /** + * @phpstan-assert-if-true int $x + * @return true + */ + public function alwaysTrue(mixed $x): bool + { + return true; + } + + /** + * @phpstan-assert-if-false int $x + * @return false + */ + public function alwaysFalse(mixed $x): bool + { + return false; + } + + /** @phpstan-assert-if-true int $x */ + public function untyped(mixed $x) + { + return is_int($x); + } + + /** @phpstan-assert-if-true int $x */ + public function returnsString(mixed $x): string + { + return ''; + } + + /** @phpstan-assert-if-false int $x */ + public function returnsVoid(mixed $x): void + { + } + + /** @phpstan-assert-if-true int $x */ + public function returnsNullableBool(mixed $x): ?bool + { + return null; + } + + /** @phpstan-assert-if-true int $x */ + public function returnsMixed(mixed $x): mixed + { + return null; + } + + /** @phpstan-assert int $x */ + public function unconditional(mixed $x): void + { + } + +} diff --git a/tests/PHPStan/Rules/PhpDoc/data/property-assert.php b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php new file mode 100644 index 00000000000..1ddebc00722 --- /dev/null +++ b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php @@ -0,0 +1,58 @@ += 8.4 + +declare(strict_types = 1); + +namespace PropertyAssert; + +class Foo +{ + + public ?string $name = null; + + /** @phpstan-assert-if-true !null $this->name */ + public bool $hasName { + get => $this->name !== null; + } + + /** @phpstan-assert-if-false null $this->name */ + public true|false $hasNameToo { + get => $this->name !== null; + } + + /** @phpstan-assert-if-true !null $this->name */ + public string $nonBool { + get => (string) $this->name; + } + + /** + * @phpstan-assert-if-true !null $this->name + * @phpstan-assert-if-false null $this->name + */ + public ?bool $nullableBool { + get => $this->name !== null; + } + + /** @phpstan-assert-if-true !null $this->name */ + public bool $plain = false; + + /** @phpstan-assert-if-true !null $this->unknown */ + public bool $unknownProperty { + get => true; + } + + /** @phpstan-assert-if-true !null $name */ + public bool $unknownParameter { + get => true; + } + + /** @phpstan-assert-if-true string|null $this->name */ + public bool $alreadyNarrowed { + get => $this->name !== null; + } + + public bool $hookDocBlock { + /** @phpstan-assert-if-true int $this->name */ + get => $this->name !== null; + } + +} diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php index 42ccfe9d1f9..ff85a405c43 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleConfigPhpTest.php @@ -5,6 +5,7 @@ use PHPStan\Php\PhpVersion; use PHPStan\Rules\Methods\MethodParameterComparisonHelper; use PHPStan\Rules\Methods\OverridingMethodCheck; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; @@ -24,6 +25,7 @@ protected function getRule(): Rule $phpVersion, new OverridingMethodCheck(), new MethodParameterComparisonHelper($phpVersion), + new OverridingAssertsCheck(), true, true, $this->checkMissingOverridePropertyAttribute, diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php index 75364cf12b9..db5fe84813e 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php @@ -5,6 +5,7 @@ use PHPStan\Php\PhpVersion; use PHPStan\Rules\Methods\MethodParameterComparisonHelper; use PHPStan\Rules\Methods\OverridingMethodCheck; +use PHPStan\Rules\PhpDoc\OverridingAssertsCheck; use PHPStan\Rules\Rule; use PHPStan\Testing\RuleTestCase; use PHPUnit\Framework\Attributes\DataProvider; @@ -33,6 +34,7 @@ protected function getRule(): Rule $phpVersion, new OverridingMethodCheck(), new MethodParameterComparisonHelper($phpVersion), + new OverridingAssertsCheck(), true, $this->reportMaybes, $this->checkMissingOverridePropertyAttribute, @@ -524,4 +526,31 @@ public function testFixHookOverrideAttribute(): void $this->fix(__DIR__ . '/data/property-hook-override-attr.php', __DIR__ . '/data/property-hook-override-attr.php.fixed'); } + #[RequiresPhp('>= 8.4.0')] + public function testAssertTags(): void + { + $this->reportMaybes = true; + $this->analyse([__DIR__ . '/data/property-assert-override.php'], [ + [ + 'Property PropertyAssertOverride\\MoreTags::$sponsored does not narrow $this->sponsorName when it is false, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to null.', + 37, + 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', + ], + [ + 'Property PropertyAssertOverride\\OtherTags::$sponsored does not narrow $this->sponsorName when it is false, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to null.', + 47, + 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', + ], + [ + 'Property PropertyAssertOverride\\OtherTags::$sponsored does not narrow $this->sponsorName when it is true, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to mixed~null.', + 47, + 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', + ], + [ + 'Property PropertyAssertOverride\\NarrowerValue::$hasValue narrows $this->value to mixed~int<1, max> when it is false, but overridden property PropertyAssertOverride\\HasValue::$hasValue narrows it to mixed~int.', + 78, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Properties/data/property-assert-override.php b/tests/PHPStan/Rules/Properties/data/property-assert-override.php new file mode 100644 index 00000000000..ad8dad93a97 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/property-assert-override.php @@ -0,0 +1,82 @@ += 8.4 + +declare(strict_types = 1); + +namespace PropertyAssertOverride; + +class Sponsor +{ + + public ?string $sponsorName = null; + + public ?string $sponsorUrl = null; + + /** @phpstan-assert-if-true !null $this->sponsorName */ + public bool $sponsored { + get => $this->sponsorName !== null; + } + +} + +class Inherits extends Sponsor +{ + + public bool $sponsored { + get => $this->sponsorName !== null && $this->sponsorUrl !== null; + } + +} + +class MoreTags extends Sponsor +{ + + /** + * @phpstan-assert-if-true !null $this->sponsorName + * @phpstan-assert-if-true !null $this->sponsorUrl + */ + public bool $sponsored { + get => $this->sponsorName !== null && $this->sponsorUrl !== null; + } + +} + +class OtherTags extends Sponsor +{ + + /** @phpstan-assert-if-true !null $this->sponsorUrl */ + public bool $sponsored { + get => $this->sponsorUrl !== null; + } + +} + +class NeverTrue extends Sponsor +{ + + public false $sponsored { + get => false; + } + +} + +interface HasValue +{ + + /** @phpstan-assert-if-true int $this->value */ + public bool $hasValue { get; } + + public int|string|null $value { get; } + +} + +final class NarrowerValue implements HasValue +{ + + public int|string|null $value = null; + + /** @phpstan-assert-if-true positive-int $this->value */ + public bool $hasValue { + get => is_int($this->value) && $this->value > 0; + } + +} diff --git a/turbo-ext/src/DefaultNarrowingHelper.cpp b/turbo-ext/src/DefaultNarrowingHelper.cpp index eb4ff80d9f8..089885d2b7d 100644 --- a/turbo-ext/src/DefaultNarrowingHelper.cpp +++ b/turbo-ext/src/DefaultNarrowingHelper.cpp @@ -1178,7 +1178,9 @@ class DefaultNarrowingHelper zv::Arr argsMap = zv::Arr::empty(); zv::Val parameters = pt_parameters_acceptor_call(parametersAcceptor, PT_PA_GET_PARAMETERS); if (UNEXPECTED(parameters.isUndef())) return zv::Val(); - if (UNEXPECTED(!mapArgumentsToParameters(call, parametersAcceptor, parameters.raw(), true, argsMap))) return zv::Val(); + /* a property fetch (its get hook's asserts) has no arguments */ + bool isPropertyFetch = isA(call, PT_CLASS_PROPERTY_FETCH); + if (!isPropertyFetch && UNEXPECTED(!mapArgumentsToParameters(call, parametersAcceptor, parameters.raw(), true, argsMap))) return zv::Val(); if (Z_TYPE_P(parameters.raw()) == IS_ARRAY) { for (zv::ArrayEntry entry : zv::ArrRef(parameters.raw())) { zval *parameter = entry.value().deref().raw(); @@ -1199,7 +1201,7 @@ class DefaultNarrowingHelper } } - if (isA(call, PT_CLASS_METHOD_CALL)) { + if (isPropertyFetch || isA(call, PT_CLASS_METHOD_CALL)) { zv::Arr thisList = zv::Arr::create(1); thisList.push(zv::Ref(varOf(call))); argsMap.set("this", zv::Val(std::move(thisList))); diff --git a/turbo-ext/src/PhpClassReflectionExtension.cpp b/turbo-ext/src/PhpClassReflectionExtension.cpp index 6a86a449273..d2d58421898 100644 --- a/turbo-ext/src/PhpClassReflectionExtension.cpp +++ b/turbo-ext/src/PhpClassReflectionExtension.cpp @@ -1079,6 +1079,12 @@ class PhpClassReflectionExtension } } + if (kind == 0 && Z_TYPE_P(resolvedPhpDoc.raw()) != IS_NULL) { + zv::Val changed = call(hook.raw(), PT_LC("changepropertygethookasserts"), 1, resolvedPhpDoc.raw()); + if (UNEXPECTED(changed.isUndef())) return zv::Val(); + hook = std::move(changed); + } + if (kind == 0) { getHook = std::move(hook); } else { diff --git a/turbo-ext/src/PropertyFetchHandler.cpp b/turbo-ext/src/PropertyFetchHandler.cpp index f4e54f38560..562e330cf6b 100644 --- a/turbo-ext/src/PropertyFetchHandler.cpp +++ b/turbo-ext/src/PropertyFetchHandler.cpp @@ -10,7 +10,7 @@ * what the PHP closures capture: the issetability descriptor's reflection * resolver ($this, $expr), the typeCallback ($this, $expr, $varResult, * $nameResult, $beforeScope) and the specifyTypesCallback ($this, $expr, - * $beforeScope); the $shortCircuit / $resolveProperty closures the + * $beforeScope, $varResult, $getHook); the $shortCircuit / $resolveProperty closures the * typeCallback creates and calls itself are inlined, as is the private * propertyFetchType(). * @@ -158,10 +158,11 @@ class PropertyFetchHandler int nameIsIdentifier = isIdentifier(name); if (UNEXPECTED(nameIsIdentifier < 0)) return zv::Val(); bool mayShortCircuit = false; + zv::Val getHook = zv::Val::null(); if (nameIsIdentifier) { zend_long supportsPropertyHooks = pt_mutating_scope_php_versions_trinary(Z_OBJ_P(scopeBeforeVar), PT_LC("supportspropertyhooks")); if (UNEXPECTED(supportsPropertyHooks < 0)) return zv::Val(); - if (mayHavePropertyHooks(supportsPropertyHooks) && UNEXPECTED(!addGetHookPoints(nodeScopeResolver, expr, name, varResult, scopeBeforeVar, throwPoints, impurePoints))) return zv::Val(); + if (mayHavePropertyHooks(supportsPropertyHooks) && UNEXPECTED(!addGetHookPoints(nodeScopeResolver, expr, name, varResult, scopeBeforeVar, throwPoints, impurePoints, getHook))) return zv::Val(); } else if (nameResult != NULL) { // a fetch that is a link in a nullsafe chain may never run - see // MethodCallHandler::processExpr(). Only the dynamic name is skipped @@ -224,7 +225,7 @@ class PropertyFetchHandler zval null = {}; ZVAL_NULL(&null); zv::Val typeCallback = pt_native_closure(&typeCallbackBody, self, expr, varResult, nameResult != NULL ? nameResult : &null, beforeScope); - zv::Val specifyTypesCallback = pt_native_closure(&specifyTypesCallbackBody, self, expr, beforeScope); + zv::Val specifyTypesCallback = pt_native_closure(&specifyTypesCallbackBody, self, expr, beforeScope, varResult, getHook.raw()); pt_expression_result_args args(scope.raw(), beforeScope, expr, hasYield, isAlwaysTerminating, throwPoints.raw(), impurePoints.raw(), typeCallback.raw(), specifyTypesCallback.raw()); args.withVariableFlow(variableFlow.raw()).withContainsNullsafe(containsNullsafe).withIssetabilityDescriptor(issetabilityDescriptor.raw()); @@ -295,8 +296,9 @@ class PropertyFetchHandler /* the Identifier branch of composeResult() while property hooks are * supported: the get hook's throw points merged into $throwPoints and - * its impure points into $impurePoints; false = pending exception */ - [[nodiscard]] bool addGetHookPoints(zval *nodeScopeResolver, zval *expr, zval *name, zval *varResult, zval *scopeBeforeVar, zv::Val &throwPoints, zv::Val &impurePoints) const + * its impure points into $impurePoints, the get hook itself into + * $getHook; false = pending exception */ + [[nodiscard]] bool addGetHookPoints(zval *nodeScopeResolver, zval *expr, zval *name, zval *varResult, zval *scopeBeforeVar, zv::Val &throwPoints, zv::Val &impurePoints, zv::Val &getHook) const { zval *propertyName = identifierName(name); if (UNEXPECTED(propertyName == NULL)) return false; @@ -310,6 +312,15 @@ class PropertyFetchHandler if (UNEXPECTED(propertyReflection.isUndef())) return false; if (propertyReflection.isNull()) return true; + zval hookKind; + ZVAL_STR(&hookKind, pt_pfh_get); + zv::Val hasHook = pt_type_call(Z_OBJ_P(propertyReflection.raw()), PT_LC("hashook"), 1, &hookKind); + if (UNEXPECTED(hasHook.isUndef())) return false; + if (zend_is_true(hasHook.raw())) { + getHook = pt_type_call(Z_OBJ_P(propertyReflection.raw()), PT_LC("gethook"), 1, &hookKind); + if (UNEXPECTED(getHook.isUndef())) return false; + } + zv::Val propertyDeclaringClass = pt_property_reflection_get_declaring_class(propertyReflection.raw()); if (UNEXPECTED(propertyDeclaringClass.isUndef())) return false; if (UNEXPECTED(!propertyDeclaringClass.ref().isObject())) { @@ -476,14 +487,53 @@ class PropertyFetchHandler type.intoReturnValue(return_value); } + /* Mirrors specifyTypes(): the default narrowing of the fetch, plus the + * @phpstan-assert tags of the property's get hook */ + zv::Val specifyTypes(zval *expr, zval *varResult, zval *getHook, zval *context, zval *beforeScope, bool nativeTypesPromoted) const + { + zval *helper = OBJ_PROP_NUM(self, slots::defaultNarrowingHelper); + zv::Val defaultTypes = pt_default_narrowing_helper_specify_default_types_with_nullsafe_fan(helper, expr, context, beforeScope, nativeTypesPromoted); + if (UNEXPECTED(defaultTypes.isUndef())) return zv::Val(); + if (Z_TYPE_P(getHook) == IS_NULL) return defaultTypes; + zv::Val assertions = pt_extended_method_reflection_call(getHook, PT_MR_GET_ASSERTS); + if (UNEXPECTED(assertions.isUndef())) return zv::Val(); + zv::Val all = assertionsGetAll(assertions.raw()); + if (UNEXPECTED(all.isUndef())) return zv::Val(); + if (Z_TYPE_P(all.raw()) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_P(all.raw())) == 0) return defaultTypes; + + zval *scope = beforeScope; + zv::Val promotedScope; + if (nativeTypesPromoted) { + promotedScope = pt_mutating_scope_do_not_treat_phpdoc_types_as_certain(Z_OBJ_P(beforeScope)); + if (UNEXPECTED(promotedScope.isUndef())) return zv::Val(); + scope = promotedScope.raw(); + } + zv::Val receiverType = pt_expression_result_get_type_on_scope(varResult, scope, nativeTypesPromoted); + if (UNEXPECTED(receiverType.isUndef())) return zv::Val(); + bool mayHaveBeenSkipped; + if (UNEXPECTED(!pt_default_narrowing_helper_call_may_have_been_skipped(helper, varResult, receiverType.raw(), context, mayHaveBeenSkipped))) return zv::Val(); + if (mayHaveBeenSkipped) return defaultTypes; + + zv::Val variant = pt_extended_method_reflection_call(getHook, PT_MR_GET_ONLY_VARIANT); + if (UNEXPECTED(variant.isUndef())) return zv::Val(); + zv::Val assertTypes = pt_default_narrowing_helper_specify_types_from_asserts(helper, context, expr, assertions.raw(), variant.raw(), scope); + if (UNEXPECTED(assertTypes.isUndef())) return zv::Val(); + if (assertTypes.isNull()) return defaultTypes; + zv::Val united = pt_specified_types_union_with(Z_OBJ_P(assertTypes.raw()), defaultTypes.raw()); + if (UNEXPECTED(united.isUndef())) return zv::Val(); + zv::Val rootExpr = pt_specified_types_get_root_expr(Z_OBJ_P(assertTypes.raw())); + if (UNEXPECTED(rootExpr.isUndef())) return zv::Val(); + return pt_specified_types_set_root_expr(Z_OBJ_P(united.raw()), rootExpr.raw()); + } + /* fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => - * $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, - * $context, $beforeScope, $nativeTypesPromoted) — captures: $this, $expr, - * $beforeScope */ + * $this->specifyTypes($expr, $varResult, $getHook, $context, $beforeScope, + * $nativeTypesPromoted) — captures: $this, $expr, $beforeScope, $varResult, + * $getHook */ static void specifyTypesCallbackBody(zval *captures, uint32_t argc, zval *argv, zval *return_value) { if (UNEXPECTED(!requireArguments(argc, 2, pt_pfh_closure_name))) return; - zv::Val specifiedTypes = pt_default_narrowing_helper_specify_default_types_with_nullsafe_fan(OBJ_PROP_NUM(Z_OBJ(captures[0]), slots::defaultNarrowingHelper), &captures[1], &argv[0], &captures[2], zend_is_true(&argv[1])); + zv::Val specifiedTypes = PropertyFetchHandler(Z_OBJ(captures[0])).specifyTypes(&captures[1], &captures[3], &captures[4], &argv[0], &captures[2], zend_is_true(&argv[1])); if (UNEXPECTED(specifiedTypes.isUndef())) return; specifiedTypes.intoReturnValue(return_value); } diff --git a/turbo-ext/src/generated/DefaultNarrowingHelper.h b/turbo-ext/src/generated/DefaultNarrowingHelper.h index b5947d3151c..725faa6b37e 100644 --- a/turbo-ext/src/generated/DefaultNarrowingHelper.h +++ b/turbo-ext/src/generated/DefaultNarrowingHelper.h @@ -93,20 +93,21 @@ inline constexpr char strings[] = "varResult\0" /* 1067 */ "createIssetSingleSubjectNonTrueTypes\0" /* 1077 */ "call\0" /* 1114 */ - "PhpParser\\Node\\Expr\\CallLike\0" /* 1119 */ - "assertions\0" /* 1148 */ - "PHPStan\\Reflection\\Assertions\0" /* 1159 */ - "parametersAcceptor\0" /* 1189 */ - "PHPStan\\Reflection\\ParametersAcceptor\0" /* 1208 */ - "specifyTypesFromAsserts\0" /* 1246 */ - "specifyTypesFromConditionalReturnType\0" /* 1270 */ - "conditionalType\0" /* 1308 */ - "PHPStan\\Type\\ConditionalTypeForParameter\0" /* 1324 */ - "leftType\0" /* 1365 */ - "rightType\0" /* 1374 */ - "argumentExpr\0" /* 1384 */ - "getConditionalSpecifiedTypes\0" /* 1397 */ - "mayRememberCallSubject"; /* 1426 */ + "PhpParser\\Node\\Expr\\CallLike|PhpParser\\Node\\Expr\\PropertyFetch\0" /* 1119 */ + "assertions\0" /* 1182 */ + "PHPStan\\Reflection\\Assertions\0" /* 1193 */ + "parametersAcceptor\0" /* 1223 */ + "PHPStan\\Reflection\\ParametersAcceptor\0" /* 1242 */ + "specifyTypesFromAsserts\0" /* 1280 */ + "PhpParser\\Node\\Expr\\CallLike\0" /* 1304 */ + "specifyTypesFromConditionalReturnType\0" /* 1333 */ + "conditionalType\0" /* 1371 */ + "PHPStan\\Type\\ConditionalTypeForParameter\0" /* 1387 */ + "leftType\0" /* 1428 */ + "rightType\0" /* 1437 */ + "argumentExpr\0" /* 1447 */ + "getConditionalSpecifiedTypes\0" /* 1460 */ + "mayRememberCallSubject"; /* 1489 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 12), /* __construct $exprPrinter */ reg::packed(45, MAY_BE_BOOL), /* __construct $rememberPossiblyImpureFunctionValues */ @@ -195,20 +196,20 @@ inline constexpr reg::PackedArg args[] = { reg::packed(277, 0, 278), /* createIssetSingleSubjectNonTrueTypes return */ reg::packed(231, 0, 239), /* specifyTypesFromAsserts $context */ reg::packed(1114, 0, 1119), /* specifyTypesFromAsserts $call */ - reg::packed(1148, 0, 1159), /* specifyTypesFromAsserts $assertions */ - reg::packed(1189, 0, 1208), /* specifyTypesFromAsserts $parametersAcceptor */ + reg::packed(1182, 0, 1193), /* specifyTypesFromAsserts $assertions */ + reg::packed(1223, 0, 1242), /* specifyTypesFromAsserts $parametersAcceptor */ reg::packed(177, 0, 402), /* specifyTypesFromAsserts $scope */ reg::packed(277, MAY_BE_NULL, 278), /* specifyTypesFromAsserts return */ reg::packed(231, 0, 239), /* specifyTypesFromConditionalReturnType $context */ - reg::packed(1114, 0, 1119), /* specifyTypesFromConditionalReturnType $call */ - reg::packed(1189, 0, 1208), /* specifyTypesFromConditionalReturnType $parametersAcceptor */ + reg::packed(1114, 0, 1304), /* specifyTypesFromConditionalReturnType $call */ + reg::packed(1223, 0, 1242), /* specifyTypesFromConditionalReturnType $parametersAcceptor */ reg::packed(177, 0, 402), /* specifyTypesFromConditionalReturnType $scope */ reg::packed(277, MAY_BE_NULL, 278), /* specifyTypesFromConditionalReturnType return */ - reg::packed(1308, 0, 1324), /* getConditionalSpecifiedTypes $conditionalType */ - reg::packed(1365, 0, 585), /* getConditionalSpecifiedTypes $leftType */ - reg::packed(1374, 0, 585), /* getConditionalSpecifiedTypes $rightType */ + reg::packed(1371, 0, 1387), /* getConditionalSpecifiedTypes $conditionalType */ + reg::packed(1428, 0, 585), /* getConditionalSpecifiedTypes $leftType */ + reg::packed(1437, 0, 585), /* getConditionalSpecifiedTypes $rightType */ reg::packed(177, 0, 402), /* getConditionalSpecifiedTypes $scope */ - reg::packed(1384, 0, 211), /* getConditionalSpecifiedTypes $argumentExpr */ + reg::packed(1447, 0, 211), /* getConditionalSpecifiedTypes $argumentExpr */ reg::packed(277, MAY_BE_NULL, 278), /* getConditionalSpecifiedTypes return */ reg::packed(177, 0, 402), /* mayRememberCallSubject $scope */ reg::packed(330, 0, 211), /* mayRememberCallSubject $expr */ @@ -238,10 +239,10 @@ inline constexpr sigtab::Sig captureChainResults = { { 970 /* captureChainResult inline constexpr sigtab::Sig buildChainTypeReader = { { 990 /* buildChainTypeReader */, 2, 69, 2, 71, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig createIssetTruthyChainTypes = { { 1039 /* createIssetTruthyChainTypes */, 5, 72, 5, 77, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig createIssetSingleSubjectNonTrueTypes = { { 1077 /* createIssetSingleSubjectNonTrueTypes */, 6, 78, 6, 84, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig specifyTypesFromAsserts = { { 1246 /* specifyTypesFromAsserts */, 5, 85, 5, 90, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig specifyTypesFromConditionalReturnType = { { 1270 /* specifyTypesFromConditionalReturnType */, 4, 91, 4, 95, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getConditionalSpecifiedTypes = { { 1397 /* getConditionalSpecifiedTypes */, 5, 96, 5, 101, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig mayRememberCallSubject = { { 1426 /* mayRememberCallSubject */, 2, 102, 2, 104, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig specifyTypesFromAsserts = { { 1280 /* specifyTypesFromAsserts */, 5, 85, 5, 90, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig specifyTypesFromConditionalReturnType = { { 1333 /* specifyTypesFromConditionalReturnType */, 4, 91, 4, 95, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getConditionalSpecifiedTypes = { { 1460 /* getConditionalSpecifiedTypes */, 5, 96, 5, 101, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig mayRememberCallSubject = { { 1489 /* mayRememberCallSubject */, 2, 102, 2, 104, ZEND_ACC_PRIVATE } }; } // namespace sig } // namespace ptdecl::DefaultNarrowingHelper diff --git a/turbo-ext/src/generated/PropertyFetchHandler.h b/turbo-ext/src/generated/PropertyFetchHandler.h index 8dddf9fbb6c..e18b18549a3 100644 --- a/turbo-ext/src/generated/PropertyFetchHandler.h +++ b/turbo-ext/src/generated/PropertyFetchHandler.h @@ -69,14 +69,20 @@ inline constexpr char strings[] = "scopeBeforeVar\0" /* 697 */ "beforeScope\0" /* 712 */ "composeResult\0" /* 724 */ - "result\0" /* 738 */ - "PHPStan\\Dependency\\Dependencies\0" /* 745 */ - "getDependencies\0" /* 777 */ - "fetchedOnType\0" /* 793 */ - "PHPStan\\Type\\Type\0" /* 807 */ - "propertyName\0" /* 825 */ - "propertyFetch\0" /* 838 */ - "propertyFetchType"; /* 852 */ + "getHook\0" /* 738 */ + "PHPStan\\Reflection\\ExtendedMethodReflection\0" /* 746 */ + "PHPStan\\Analyser\\TypeSpecifierContext\0" /* 790 */ + "nativeTypesPromoted\0" /* 828 */ + "PHPStan\\Analyser\\SpecifiedTypes\0" /* 848 */ + "specifyTypes\0" /* 880 */ + "result\0" /* 893 */ + "PHPStan\\Dependency\\Dependencies\0" /* 900 */ + "getDependencies\0" /* 932 */ + "fetchedOnType\0" /* 948 */ + "PHPStan\\Type\\Type\0" /* 962 */ + "propertyName\0" /* 980 */ + "propertyFetch\0" /* 993 */ + "propertyFetchType"; /* 1007 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 25), /* __construct $propertyReflectionFinder */ reg::packed(75, 0, 99), /* __construct $expressionResultFactory */ @@ -100,16 +106,23 @@ inline constexpr reg::PackedArg args[] = { reg::packed(697, 0, 460), /* composeResult $scopeBeforeVar */ reg::packed(712, 0, 460), /* composeResult $beforeScope */ reg::packed(366, 0, 596), /* composeResult return */ + reg::packed(341, 0, 642), /* specifyTypes $expr */ + reg::packed(676, 0, 596), /* specifyTypes $varResult */ + reg::packed(738, MAY_BE_NULL, 746), /* specifyTypes $getHook */ + reg::packed(553, 0, 790), /* specifyTypes $context */ + reg::packed(712, 0, 460), /* specifyTypes $beforeScope */ + reg::packed(828, MAY_BE_BOOL), /* specifyTypes $nativeTypesPromoted */ + reg::packed(366, 0, 848), /* specifyTypes return */ reg::packed(454, 0, 460), /* getDependencies $scope */ reg::packed(341, 0, 642), /* getDependencies $expr */ reg::packed(676, 0, 596), /* getDependencies $varResult */ - reg::packed(738, 0, 596), /* getDependencies $result */ - reg::packed(366, MAY_BE_NULL, 745), /* getDependencies return */ + reg::packed(893, 0, 596), /* getDependencies $result */ + reg::packed(366, MAY_BE_NULL, 900), /* getDependencies return */ reg::packed(454, 0, 460), /* propertyFetchType $scope */ - reg::packed(793, 0, 807), /* propertyFetchType $fetchedOnType */ - reg::packed(825, MAY_BE_STRING), /* propertyFetchType $propertyName */ - reg::packed(838, 0, 642), /* propertyFetchType $propertyFetch */ - reg::packed(366, MAY_BE_NULL, 807), /* propertyFetchType return */ + reg::packed(948, 0, 962), /* propertyFetchType $fetchedOnType */ + reg::packed(980, MAY_BE_STRING), /* propertyFetchType $propertyName */ + reg::packed(993, 0, 642), /* propertyFetchType $propertyFetch */ + reg::packed(366, MAY_BE_NULL, 962), /* propertyFetchType return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -120,8 +133,9 @@ inline constexpr sigtab::Sig __construct = { { 329 /* __construct */, 5, 0, 5, r inline constexpr sigtab::Sig supports = { { 367 /* supports */, 1, 5, 1, 6, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig processExpr = { { 630 /* processExpr */, 7, 7, 7, 14, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig composeResult = { { 724 /* composeResult */, 6, 15, 6, 21, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getDependencies = { { 777 /* getDependencies */, 4, 22, 4, 26, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig propertyFetchType = { { 852 /* propertyFetchType */, 4, 27, 4, 31, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig specifyTypes = { { 880 /* specifyTypes */, 6, 22, 6, 28, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getDependencies = { { 932 /* getDependencies */, 4, 29, 4, 33, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig propertyFetchType = { { 1007 /* propertyFetchType */, 4, 34, 4, 38, ZEND_ACC_PRIVATE } }; } // namespace sig } // namespace ptdecl::PropertyFetchHandler From 0debfa3a3b15ff2115dab1bde7c71d08be9631ff Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Wed, 2 Dec 2026 13:08:46 +0000 Subject: [PATCH 3/5] Do not use the true|false type, which PHP rejects, in a test fixture Amp-Thread-ID: https://ampcode.com/threads/T-01a23672-d1c1-7389-8ee4-edae78fcf9ec --- tests/PHPStan/Rules/PhpDoc/data/property-assert.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PHPStan/Rules/PhpDoc/data/property-assert.php b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php index 1ddebc00722..931af35295e 100644 --- a/tests/PHPStan/Rules/PhpDoc/data/property-assert.php +++ b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php @@ -15,8 +15,8 @@ class Foo } /** @phpstan-assert-if-false null $this->name */ - public true|false $hasNameToo { - get => $this->name !== null; + public true $alwaysTrue { + get => true; } /** @phpstan-assert-if-true !null $this->name */ From ef04449e50fcbd1bc830aada88c4641a9509fc43 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Wed, 2 Dec 2026 13:27:47 +0000 Subject: [PATCH 4/5] Inline toBoolean() in OverridingAssertsCheck so no equivalent mutant is generated Amp-Thread-ID: https://ampcode.com/threads/T-01a23672-d1c1-7389-8ee4-edae78fcf9ec --- src/Rules/PhpDoc/OverridingAssertsCheck.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Rules/PhpDoc/OverridingAssertsCheck.php b/src/Rules/PhpDoc/OverridingAssertsCheck.php index 7f7e75ca6af..feaef496a1f 100644 --- a/src/Rules/PhpDoc/OverridingAssertsCheck.php +++ b/src/Rules/PhpDoc/OverridingAssertsCheck.php @@ -73,11 +73,10 @@ public function check( $branches = [ '' => [$parentAsserts->getAsserts(), $asserts->getAsserts()], ]; - $returnBoolean = $returnType->toBoolean(); - if (!$returnBoolean->isFalse()->yes()) { + if (!$returnType->toBoolean()->isFalse()->yes()) { $branches[sprintf(' when %s true', $conditionSubject)] = [$parentAsserts->getAssertsIfTrue(), array_merge($asserts->getAsserts(), $asserts->getAssertsIfTrue())]; } - if (!$returnBoolean->isTrue()->yes()) { + if (!$returnType->toBoolean()->isTrue()->yes()) { $branches[sprintf(' when %s false', $conditionSubject)] = [$parentAsserts->getAssertsIfFalse(), array_merge($asserts->getAsserts(), $asserts->getAssertsIfFalse())]; } From 05805f5f26d5d3df254021bd43dcdac8e422e9ea Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Wed, 2 Dec 2026 14:17:15 +0000 Subject: [PATCH 5/5] Support @phpstan-assert tags only above property hooks Tags above the property itself are reported and no longer narrow, tags above a set hook are reported because it returns void. A get hook without assert tags inherits them from the get hook it overrides, like a method. Amp-Thread-ID: https://ampcode.com/threads/T-01a23672-d1c1-7389-8ee4-edae78fcf9ec --- .../Php/PhpClassReflectionExtension.php | 4 +- src/Reflection/Php/PhpMethodReflection.php | 98 ++++++++++++------- src/Rules/PhpDoc/AssertRuleHelper.php | 16 ++- src/Rules/PhpDoc/PropertyAssertRule.php | 74 ++++++-------- src/Rules/PhpDoc/PropertyHookAssertRule.php | 71 ++++++++++++++ .../Analyser/nsrt/property-hook-asserts.php | 43 ++++++-- .../Rules/PhpDoc/PropertyAssertRuleTest.php | 32 ++---- .../PhpDoc/PropertyHookAssertRuleTest.php | 89 +++++++++++++++++ .../Rules/PhpDoc/data/property-assert.php | 59 ++++++++--- .../Properties/OverridingPropertyRuleTest.php | 8 +- .../data/property-assert-override.php | 20 ++-- turbo-ext/src/PhpClassReflectionExtension.cpp | 9 +- 12 files changed, 375 insertions(+), 148 deletions(-) create mode 100644 src/Rules/PhpDoc/PropertyHookAssertRule.php create mode 100644 tests/PHPStan/Rules/PhpDoc/PropertyHookAssertRuleTest.php diff --git a/src/Reflection/Php/PhpClassReflectionExtension.php b/src/Reflection/Php/PhpClassReflectionExtension.php index cdc36897f05..d3128b6cf0e 100644 --- a/src/Reflection/Php/PhpClassReflectionExtension.php +++ b/src/Reflection/Php/PhpClassReflectionExtension.php @@ -416,9 +416,7 @@ private function createProperty( } } - if ($resolvedPhpDoc !== null) { - $getHook = $getHook->changePropertyGetHookAsserts($resolvedPhpDoc); - } + $getHook = $getHook->inheritPropertyGetHookAsserts($declaringClassReflection, $propertyReflection->getName()); } if ($betterReflection->hasHook('set')) { diff --git a/src/Reflection/Php/PhpMethodReflection.php b/src/Reflection/Php/PhpMethodReflection.php index e8f34a4cdc9..b8d08abd587 100644 --- a/src/Reflection/Php/PhpMethodReflection.php +++ b/src/Reflection/Php/PhpMethodReflection.php @@ -7,6 +7,7 @@ use PHPStan\DependencyInjection\GenerateFactory; use PHPStan\Internal\DeprecatedAttributeHelper; use PHPStan\PhpDoc\ResolvedPhpDocBlock; +use PHPStan\PhpDoc\Tag\AssertTag; use PHPStan\Reflection\Assertions; use PHPStan\Reflection\AttributeReflection; use PHPStan\Reflection\AttributeReflectionFactory; @@ -27,7 +28,9 @@ use PHPStan\Turbo\ReferencedByTurboExtension; use PHPStan\Type\ArrayType; use PHPStan\Type\BooleanType; +use PHPStan\Type\Generic\TemplateTypeHelper; use PHPStan\Type\Generic\TemplateTypeMap; +use PHPStan\Type\Generic\TemplateTypeVariance; use PHPStan\Type\IntegerType; use PHPStan\Type\MixedType; use PHPStan\Type\ObjectWithoutClassType; @@ -38,6 +41,7 @@ use PHPStan\Type\VoidType; use ReflectionException; use function array_map; +use function array_unshift; use function explode; use function in_array; use function strtolower; @@ -547,48 +551,72 @@ public function changePropertySetHookPhpDocType(string $parameterName, Type $php ); } - /** The property's @phpstan-assert tags apply to its get hook unless the hook declares its own. */ - public function changePropertyGetHookAsserts(ResolvedPhpDocBlock $propertyPhpDoc): self + /** A get hook without @phpstan-assert tags inherits them from the get hook of the property it overrides, like a method does. */ + public function inheritPropertyGetHookAsserts(ClassReflection $declaringClass, string $propertyName): self { if ($this->asserts->getAll() !== []) { return $this; } - $asserts = Assertions::createFromResolvedPhpDocBlock($propertyPhpDoc); - if ($asserts->getAll() === []) { - return $this; + $ancestors = $declaringClass->getImmediateInterfaces(); + $parent = $declaringClass->getParentClass(); + if ($parent !== null) { + array_unshift($ancestors, $parent); } - return new self( - $this->initializerExprTypeResolver, - $this->declaringClass, - $this->declaringTrait, - $this->reflection, - $this->reflectionProvider, - $this->attributeReflectionFactory, - $this->allowedConstantsMapProvider, - $this->templateTypeMap, - $this->phpDocParameterTypes, - $this->phpDocReturnType, - $this->phpDocThrowType, - $this->resolvedPhpDocBlock, - $this->deprecatedDescription, - $this->isDeprecated, - $this->isInternal, - $this->isFinal, - $this->isPure, - $asserts, - $this->acceptsNamedArguments, - $this->selfOutType, - $this->phpDocComment, - $this->phpDocParameterOutTypes, - $this->immediatelyInvokedCallableParameters, - $this->phpDocClosureThisTypeParameters, - $this->attributes, - $this->pureUnlessCallableIsImpureParameters, - $this->pureUnlessParameterPassedParameters, - $this->effects, - ); + foreach ($ancestors as $ancestor) { + if (!$ancestor->hasNativeProperty($propertyName)) { + continue; + } + $property = $ancestor->getNativeProperty($propertyName); + if ($property->isPrivate() || !$property->hasHook('get')) { + continue; + } + $assertTags = $property->getHook('get')->getAsserts()->getAll(); + if ($assertTags === []) { + continue; + } + + $asserts = Assertions::createFromAssertTags(array_map(static fn (AssertTag $tag): AssertTag => $tag->withType(TemplateTypeHelper::resolveTemplateTypes( + $tag->getType(), + $ancestor->getActiveTemplateTypeMap(), + $ancestor->getCallSiteVarianceMap(), + TemplateTypeVariance::createCovariant(), + ))->toImplicit(), $assertTags)); + + return new self( + $this->initializerExprTypeResolver, + $this->declaringClass, + $this->declaringTrait, + $this->reflection, + $this->reflectionProvider, + $this->attributeReflectionFactory, + $this->allowedConstantsMapProvider, + $this->templateTypeMap, + $this->phpDocParameterTypes, + $this->phpDocReturnType, + $this->phpDocThrowType, + $this->resolvedPhpDocBlock, + $this->deprecatedDescription, + $this->isDeprecated, + $this->isInternal, + $this->isFinal, + $this->isPure, + $asserts, + $this->acceptsNamedArguments, + $this->selfOutType, + $this->phpDocComment, + $this->phpDocParameterOutTypes, + $this->immediatelyInvokedCallableParameters, + $this->phpDocClosureThisTypeParameters, + $this->attributes, + $this->pureUnlessCallableIsImpureParameters, + $this->pureUnlessParameterPassedParameters, + $this->effects, + ); + } + + return $this; } public function getAttributes(): array diff --git a/src/Rules/PhpDoc/AssertRuleHelper.php b/src/Rules/PhpDoc/AssertRuleHelper.php index ebf9945e5eb..e4a0bb28d1f 100644 --- a/src/Rules/PhpDoc/AssertRuleHelper.php +++ b/src/Rules/PhpDoc/AssertRuleHelper.php @@ -242,11 +242,10 @@ public function checkConditionalAssertsReturnType(Assertions $asserts, Type $ret $tagNames = []; foreach ($asserts->getAll() as $assert) { - if ($assert->getIf() === AssertTag::IF_TRUE) { - $tagNames[] = '@phpstan-assert-if-true'; - } elseif ($assert->getIf() === AssertTag::IF_FALSE) { - $tagNames[] = '@phpstan-assert-if-false'; + if ($assert->getIf() === AssertTag::NULL) { + continue; } + $tagNames[] = $this->getTagName($assert); } $errors = []; @@ -263,4 +262,13 @@ public function checkConditionalAssertsReturnType(Assertions $asserts, Type $ret return $errors; } + public function getTagName(AssertTag $assert): string + { + return [ + AssertTag::NULL => '@phpstan-assert', + AssertTag::IF_TRUE => '@phpstan-assert-if-true', + AssertTag::IF_FALSE => '@phpstan-assert-if-false', + ][$assert->getIf()]; + } + } diff --git a/src/Rules/PhpDoc/PropertyAssertRule.php b/src/Rules/PhpDoc/PropertyAssertRule.php index 956105692af..78a5a942229 100644 --- a/src/Rules/PhpDoc/PropertyAssertRule.php +++ b/src/Rules/PhpDoc/PropertyAssertRule.php @@ -6,11 +6,9 @@ use PHPStan\Analyser\Scope; use PHPStan\DependencyInjection\RegisteredRule; use PHPStan\Node\ClassPropertyNode; -use PHPStan\PhpDoc\Tag\AssertTag; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; use PHPStan\Type\FileTypeMapper; -use function array_merge; use function array_unique; use function sprintf; @@ -35,56 +33,40 @@ public function getNodeType(): string public function processNode(Node $node, Scope $scope): array { - $classReflection = $node->getClassReflection(); - $propertyReflection = $classReflection->getNativeProperty($node->getName()); - $propertyDescription = sprintf('property %s::$%s', $classReflection->getDisplayName(), $node->getName()); - - if (!$propertyReflection->hasHook('get')) { - $phpDoc = $node->getPhpDoc(); - if ($phpDoc === null) { - return []; - } + $phpDoc = $node->getPhpDoc(); + if ($phpDoc === null) { + return []; + } - $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc( - $scope->getFile(), - $classReflection->getName(), - $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null, - null, - $phpDoc, - ); + $classReflection = $node->getClassReflection(); + $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc( + $scope->getFile(), + $classReflection->getName(), + $scope->isInTrait() ? $scope->getTraitReflection()->getName() : null, + null, + $phpDoc, + ); - $tagNames = []; - foreach ($resolvedPhpDoc->getAssertTags() as $assertTag) { - $tagNames[] = [ - AssertTag::NULL => '@phpstan-assert', - AssertTag::IF_TRUE => '@phpstan-assert-if-true', - AssertTag::IF_FALSE => '@phpstan-assert-if-false', - ][$assertTag->getIf()]; - } + $tagNames = []; + foreach ($resolvedPhpDoc->getAssertTags() as $assertTag) { + $tagNames[] = $this->helper->getTagName($assertTag); + } - $errors = []; - foreach (array_unique($tagNames) as $tagName) { - $errors[] = RuleErrorBuilder::message(sprintf( - 'PHPDoc tag %s above %s is supported only on properties with a get hook.', - $tagName, - $propertyDescription, - ))->identifier('assert.propertyWithoutGetHook')->build(); + $errors = []; + foreach (array_unique($tagNames) as $tagName) { + $error = RuleErrorBuilder::message(sprintf( + 'PHPDoc tag %s above property %s::$%s is not supported.', + $tagName, + $classReflection->getDisplayName(), + $node->getName(), + ))->identifier('assert.property'); + if ($classReflection->getNativeProperty($node->getName())->hasHook('get')) { + $error->tip('Put it above the get hook instead.'); } - - return $errors; + $errors[] = $error->build(); } - $getHook = $propertyReflection->getHook('get'); - - return array_merge( - $this->helper->check($scope, $node, $getHook, $getHook->getOnlyVariant()), - $this->helper->checkConditionalAssertsReturnType( - $getHook->getAsserts(), - $propertyReflection->getReadableType(), - $propertyDescription, - 'type', - ), - ); + return $errors; } } diff --git a/src/Rules/PhpDoc/PropertyHookAssertRule.php b/src/Rules/PhpDoc/PropertyHookAssertRule.php new file mode 100644 index 00000000000..d6106a17b44 --- /dev/null +++ b/src/Rules/PhpDoc/PropertyHookAssertRule.php @@ -0,0 +1,71 @@ + + */ +#[RegisteredRule(level: 2)] +final class PropertyHookAssertRule implements Rule +{ + + public function __construct( + private AssertRuleHelper $helper, + ) + { + } + + public function getNodeType(): string + { + return InPropertyHookNode::class; + } + + public function processNode(Node $node, Scope $scope): array + { + $propertyReflection = $node->getPropertyReflection(); + // the scope's hook reflection has no asserts, the property's has them resolved and inherited + $isSetHook = $node->getOriginalNode()->name->toLowerString() === 'set'; + $hookReflection = $propertyReflection->getHook($isSetHook ? 'set' : 'get'); + $propertyDescription = sprintf('property %s::$%s', $node->getClassReflection()->getDisplayName(), $propertyReflection->getName()); + + if ($isSetHook) { + // a set hook returns void and runs on assignment, there is no result to narrow by + $tagNames = []; + foreach ($hookReflection->getAsserts()->getAll() as $assertTag) { + $tagNames[] = $this->helper->getTagName($assertTag); + } + + $errors = []; + foreach (array_unique($tagNames) as $tagName) { + $errors[] = RuleErrorBuilder::message(sprintf( + 'PHPDoc tag %s above set hook of %s is not supported.', + $tagName, + $propertyDescription, + ))->identifier('assert.setHook')->build(); + } + + return $errors; + } + + return array_merge( + $this->helper->check($scope, $node, $hookReflection, $hookReflection->getOnlyVariant()), + $this->helper->checkConditionalAssertsReturnType( + $hookReflection->getAsserts(), + $propertyReflection->getReadableType(), + sprintf('get hook of %s', $propertyDescription), + 'type', + ), + ); + } + +} diff --git a/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php b/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php index 74f8118631d..ba07ad61587 100644 --- a/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php +++ b/tests/PHPStan/Analyser/nsrt/property-hook-asserts.php @@ -13,16 +13,21 @@ final class Sponsor public ?string $sponsorUrl = null; - /** - * @phpstan-assert-if-true !null $this->sponsorName - * @phpstan-assert-if-true !null $this->sponsorUrl - */ public bool $sponsored { + /** + * @phpstan-assert-if-true !null $this->sponsorName + * @phpstan-assert-if-true !null $this->sponsorUrl + */ get => $this->sponsorName !== null && $this->sponsorUrl !== null; } - /** @phpstan-assert-if-false null $this->sponsorName */ public bool $named { + /** @phpstan-assert-if-false null $this->sponsorName */ + get => $this->sponsorName !== null; + } + + /** @phpstan-assert-if-true !null $this->sponsorName */ + public bool $assertAboveProperty { get => $this->sponsorName !== null; } @@ -36,8 +41,10 @@ final class Sponsor interface HasValue { - /** @phpstan-assert-if-true int $this->value */ - public bool $hasValue { get; } + public bool $hasValue { + /** @phpstan-assert-if-true int $this->value */ + get; + } public ?int $value { get; } @@ -61,8 +68,8 @@ class Box /** @var T|null */ public ?object $value = null; - /** @phpstan-assert-if-true T $this->value */ public bool $full { + /** @phpstan-assert-if-true T $this->value */ get => $this->value !== null; } @@ -74,6 +81,16 @@ final class StdClassBox extends Box } +/** @extends Box<\DateTime> */ +final class DateTimeBox extends Box +{ + + public bool $full { + get => $this->value !== null; + } + +} + function doFoo(Sponsor $sponsor): void { if ($sponsor->sponsored) { @@ -104,12 +121,16 @@ function doBar(Sponsor $sponsor): void } else { assertType('string', $sponsor->sponsorName); } + + if ($sponsor->assertAboveProperty) { + assertType('string|null', $sponsor->sponsorName); + } } /** * @param Box<\DateTimeImmutable> $box */ -function doBaz(HasValue $hasValue, ValueImpl $valueImpl, Box $box, StdClassBox $stdClassBox): void +function doBaz(HasValue $hasValue, ValueImpl $valueImpl, Box $box, StdClassBox $stdClassBox, DateTimeBox $dateTimeBox): void { if ($hasValue->hasValue) { assertType('int', $hasValue->value); @@ -128,6 +149,10 @@ function doBaz(HasValue $hasValue, ValueImpl $valueImpl, Box $box, StdClassBox $ if ($stdClassBox->full) { assertType('stdClass', $stdClassBox->value); } + + if ($dateTimeBox->full) { + assertType('DateTime', $dateTimeBox->value); + } } function doLorem(?Sponsor $sponsor): void diff --git a/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php b/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php index 923b4b97a0b..98c5229e34b 100644 --- a/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php +++ b/tests/PHPStan/Rules/PhpDoc/PropertyAssertRuleTest.php @@ -45,36 +45,22 @@ public function testRule(): void { $this->analyse([__DIR__ . '/data/property-assert.php'], [ [ - 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$nonBool requires type bool, string given.', - 23, - ], - [ - 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', - 31, - ], - [ - 'PHPDoc tag @phpstan-assert-if-false above property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', - 31, - ], - [ - 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$plain is supported only on properties with a get hook.', + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$plain is not supported.', 36, ], [ - 'Assert references unknown $this->unknown.', - 39, - ], - [ - 'Assert references unknown parameter $name.', - 44, + 'PHPDoc tag @phpstan-assert above property PropertyAssert\\Foo::$aboveProperty is not supported.', + 43, + 'Put it above the get hook instead.', ], [ - 'Asserted type string|null for $this->name with type string|null does not narrow down the type.', - 49, + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$aboveProperty is not supported.', + 43, + 'Put it above the get hook instead.', ], [ - 'Asserted type int for $this->name with type string|null can never happen.', - 53, + 'PHPDoc tag @phpstan-assert-if-true above property PropertyAssert\\Foo::$promoted is not supported.', + 80, ], ]); } diff --git a/tests/PHPStan/Rules/PhpDoc/PropertyHookAssertRuleTest.php b/tests/PHPStan/Rules/PhpDoc/PropertyHookAssertRuleTest.php new file mode 100644 index 00000000000..933df83d364 --- /dev/null +++ b/tests/PHPStan/Rules/PhpDoc/PropertyHookAssertRuleTest.php @@ -0,0 +1,89 @@ + + */ +class PropertyHookAssertRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + $reflectionProvider = self::createReflectionProvider(); + $container = self::getContainer(); + return new PropertyHookAssertRule(new AssertRuleHelper( + $reflectionProvider, + new UnresolvableTypeHelper(), + new ClassNameCheck( + new ClassCaseSensitivityCheck($reflectionProvider, true, true), + new ClassForbiddenNameCheck($container->getExtensionsCollection(ForbiddenClassNameExtension::class)), + $reflectionProvider, + $container->getExtensionsCollection(RestrictedClassNameUsageExtension::class), + ), + new MissingTypehintCheck(true, [], true), + new GenericObjectTypeCheck(), + true, + true, + )); + } + + #[RequiresPhp('>= 8.4.0')] + public function testRule(): void + { + $this->analyse([__DIR__ . '/data/property-assert.php'], [ + [ + 'PHPDoc tag @phpstan-assert-if-true above get hook of property PropertyAssert\\Foo::$nonBool requires type bool, string given.', + 24, + ], + [ + 'PHPDoc tag @phpstan-assert-if-false above get hook of property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', + 32, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above get hook of property PropertyAssert\\Foo::$nullableBool requires type bool, bool|null given.', + 32, + ], + [ + 'Assert references unknown $this->unknown.', + 49, + ], + [ + 'Assert references unknown parameter $name.', + 54, + ], + [ + 'Asserted type string|null for $this->name with type string|null does not narrow down the type.', + 59, + ], + [ + 'Asserted type int for $this->name with type string|null can never happen.', + 64, + ], + [ + 'PHPDoc tag @phpstan-assert above set hook of property PropertyAssert\\Foo::$setHook is not supported.', + 73, + ], + [ + 'PHPDoc tag @phpstan-assert-if-true above set hook of property PropertyAssert\\Foo::$setHook is not supported.', + 73, + ], + [ + 'Assert references unknown $this->unknown.', + 92, + ], + ]); + } + +} diff --git a/tests/PHPStan/Rules/PhpDoc/data/property-assert.php b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php index 931af35295e..bfa3b021d7b 100644 --- a/tests/PHPStan/Rules/PhpDoc/data/property-assert.php +++ b/tests/PHPStan/Rules/PhpDoc/data/property-assert.php @@ -9,50 +9,87 @@ class Foo public ?string $name = null; - /** @phpstan-assert-if-true !null $this->name */ public bool $hasName { + /** @phpstan-assert-if-true !null $this->name */ get => $this->name !== null; } - /** @phpstan-assert-if-false null $this->name */ public true $alwaysTrue { + /** @phpstan-assert-if-false null $this->name */ get => true; } - /** @phpstan-assert-if-true !null $this->name */ public string $nonBool { + /** @phpstan-assert-if-true !null $this->name */ get => (string) $this->name; } - /** - * @phpstan-assert-if-true !null $this->name - * @phpstan-assert-if-false null $this->name - */ public ?bool $nullableBool { + /** + * @phpstan-assert-if-true !null $this->name + * @phpstan-assert-if-false null $this->name + */ get => $this->name !== null; } /** @phpstan-assert-if-true !null $this->name */ public bool $plain = false; - /** @phpstan-assert-if-true !null $this->unknown */ + /** + * @phpstan-assert-if-true !null $this->name + * @phpstan-assert-if-true string $this->name + * @phpstan-assert !null $this->name + */ + public bool $aboveProperty { + get => $this->name !== null; + } + public bool $unknownProperty { + /** @phpstan-assert-if-true !null $this->unknown */ get => true; } - /** @phpstan-assert-if-true !null $name */ public bool $unknownParameter { + /** @phpstan-assert-if-true !null $name */ get => true; } - /** @phpstan-assert-if-true string|null $this->name */ public bool $alreadyNarrowed { + /** @phpstan-assert-if-true string|null $this->name */ get => $this->name !== null; } - public bool $hookDocBlock { + public bool $neverHappens { /** @phpstan-assert-if-true int $this->name */ get => $this->name !== null; } + public bool $setHook { + get => $this->name !== null; + /** + * @phpstan-assert-if-true !null $this->name + * @phpstan-assert !null $this->name + */ + set { + $this->name = $value ? 'yes' : null; + } + } + + public function __construct( + /** @phpstan-assert-if-true !null $this->name */ + public bool $promoted, + ) + { + } + +} + +interface Bar +{ + + public bool $abstractHook { + /** @phpstan-assert-if-true !null $this->unknown */ + get; + } + } diff --git a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php index db5fe84813e..6f75b8a4b5d 100644 --- a/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php +++ b/tests/PHPStan/Rules/Properties/OverridingPropertyRuleTest.php @@ -533,22 +533,22 @@ public function testAssertTags(): void $this->analyse([__DIR__ . '/data/property-assert-override.php'], [ [ 'Property PropertyAssertOverride\\MoreTags::$sponsored does not narrow $this->sponsorName when it is false, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to null.', - 37, + 33, 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', ], [ 'Property PropertyAssertOverride\\OtherTags::$sponsored does not narrow $this->sponsorName when it is false, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to null.', - 47, + 46, 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', ], [ 'Property PropertyAssertOverride\\OtherTags::$sponsored does not narrow $this->sponsorName when it is true, but overridden property PropertyAssertOverride\\Sponsor::$sponsored narrows it to mixed~null.', - 47, + 46, 'PHPDoc tags @phpstan-assert* are inherited only when the overriding declaration has none of its own.', ], [ 'Property PropertyAssertOverride\\NarrowerValue::$hasValue narrows $this->value to mixed~int<1, max> when it is false, but overridden property PropertyAssertOverride\\HasValue::$hasValue narrows it to mixed~int.', - 78, + 79, ], ]); } diff --git a/tests/PHPStan/Rules/Properties/data/property-assert-override.php b/tests/PHPStan/Rules/Properties/data/property-assert-override.php index ad8dad93a97..916de613274 100644 --- a/tests/PHPStan/Rules/Properties/data/property-assert-override.php +++ b/tests/PHPStan/Rules/Properties/data/property-assert-override.php @@ -11,8 +11,8 @@ class Sponsor public ?string $sponsorUrl = null; - /** @phpstan-assert-if-true !null $this->sponsorName */ public bool $sponsored { + /** @phpstan-assert-if-true !null $this->sponsorName */ get => $this->sponsorName !== null; } @@ -30,11 +30,11 @@ class Inherits extends Sponsor class MoreTags extends Sponsor { - /** - * @phpstan-assert-if-true !null $this->sponsorName - * @phpstan-assert-if-true !null $this->sponsorUrl - */ public bool $sponsored { + /** + * @phpstan-assert-if-true !null $this->sponsorName + * @phpstan-assert-if-true !null $this->sponsorUrl + */ get => $this->sponsorName !== null && $this->sponsorUrl !== null; } @@ -43,8 +43,8 @@ class MoreTags extends Sponsor class OtherTags extends Sponsor { - /** @phpstan-assert-if-true !null $this->sponsorUrl */ public bool $sponsored { + /** @phpstan-assert-if-true !null $this->sponsorUrl */ get => $this->sponsorUrl !== null; } @@ -62,8 +62,10 @@ class NeverTrue extends Sponsor interface HasValue { - /** @phpstan-assert-if-true int $this->value */ - public bool $hasValue { get; } + public bool $hasValue { + /** @phpstan-assert-if-true int $this->value */ + get; + } public int|string|null $value { get; } @@ -74,8 +76,8 @@ final class NarrowerValue implements HasValue public int|string|null $value = null; - /** @phpstan-assert-if-true positive-int $this->value */ public bool $hasValue { + /** @phpstan-assert-if-true positive-int $this->value */ get => is_int($this->value) && $this->value > 0; } diff --git a/turbo-ext/src/PhpClassReflectionExtension.cpp b/turbo-ext/src/PhpClassReflectionExtension.cpp index d2d58421898..7183c856713 100644 --- a/turbo-ext/src/PhpClassReflectionExtension.cpp +++ b/turbo-ext/src/PhpClassReflectionExtension.cpp @@ -1079,10 +1079,11 @@ class PhpClassReflectionExtension } } - if (kind == 0 && Z_TYPE_P(resolvedPhpDoc.raw()) != IS_NULL) { - zv::Val changed = call(hook.raw(), PT_LC("changepropertygethookasserts"), 1, resolvedPhpDoc.raw()); - if (UNEXPECTED(changed.isUndef())) return zv::Val(); - hook = std::move(changed); + if (kind == 0) { + zv::Args inheritArgs{declaringClass, &propertyNameArg}; + zv::Val inherited = call(hook.raw(), PT_LC("inheritpropertygethookasserts"), 2, inheritArgs); + if (UNEXPECTED(inherited.isUndef())) return zv::Val(); + hook = std::move(inherited); } if (kind == 0) {