Skip to content
8 changes: 8 additions & 0 deletions src/Internal/Ast/ContractVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,14 @@ private function handleAssign(Node\Expr\Assign $node): void
if ($resolvedClass !== null) {
$this->scopeManager->registerInferredVarType($varName, $resolvedClass);
}
} elseif ($node->expr instanceof Node\Expr\Clone_ && $node->expr->expr instanceof Node\Expr\Variable && \is_string($node->expr->expr->name)) {
$sourceVarName = $node->expr->expr->name;
$sourceType = $this->scopeManager->getVarTypeFromScope($sourceVarName)
?? $this->scopeManager->getInferredVarType($sourceVarName);

if ($sourceType !== null) {
$this->scopeManager->registerInferredVarType($varName, $sourceType);
}
} elseif (! ($node->expr instanceof Node\Expr\AssignRef)) {
$this->scopeManager->unregisterInferredVarType($varName);
}
Expand Down
111 changes: 111 additions & 0 deletions src/Internal/Checker/MemberAssignChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@

namespace TypePHP\Internal\Checker;

use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use ReflectionProperty;
use TypePHP\Internal\Diagnostic\ErrorFactory;
use TypePHP\Internal\Diagnostic\ErrorMessage;
use TypePHP\Internal\Docblock\DocblockParser;
use TypePHP\Internal\Generics\TemplateManager;
use TypePHP\Internal\Generics\TemplateSubstitutor;
use TypePHP\Internal\Util\Config;
use TypePHP\Internal\Util\StructureMutator;
use TypePHP\Internal\Validator\TypeValidatorRegistry;
Expand Down Expand Up @@ -109,6 +115,31 @@ public static function checkProperty(
}

$currentVal = self::readPropertyValue($objectOrClass, $className, $propName);

if (
Config::isArrayValidationHybrid()
&& \is_array($currentVal)
&& \count($currentVal) > Config::HYBRID_SAMPLE_THRESHOLD
&& \count($chain) === 1
&& $chain[0][0] === 'dim'
) {
$directErr = self::validatePropertyElementMutation(
$objectOrClass,
$className,
$propName,
$chain,
$value,
$file,
$registry
);

if ($directErr instanceof ErrorMessage) {
return $directErr;
}

return $value;
}

$copy = StructureMutator::mutateCopy($currentVal, $chain, $value);

$res = InlineChecker::checkProperty($copy, $objectOrClass, $propName, $file, $registry);
Expand All @@ -120,6 +151,86 @@ public static function checkProperty(
return $value;
}

/**
* Directly validates a single element appended/assigned to a large property array in O(1).
*
* @param list<array{0: 'dim'|'prop', 1: mixed}> $chain
*/
private static function validatePropertyElementMutation(
mixed $objectOrClass,
string $className,
string $propName,
array $chain,
mixed $value,
string $file,
TypeValidatorRegistry $registry
): ?ErrorMessage {
try {
$rawTypeNode = DocblockParser::parseProperty($className, $propName);
if ($rawTypeNode === null) {
return null;
}

$typeNode = $rawTypeNode;
if (\is_object($objectOrClass)) {
$allTemplates = DocblockParser::parseClassTemplates($className);
if ($allTemplates !== []) {
$boundTemplates = TemplateManager::getBoundTemplates('none', $objectOrClass, $allTemplates);
if ($boundTemplates !== []) {
$typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates);
}
}
}

$key = $chain[0][1];
$keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : '');

if ($typeNode instanceof GenericTypeNode) {
$base = strtolower((string) $typeNode->type);

if ($base === 'list' || $base === 'non-empty-list') {
if ($key !== null && ! \is_int($key)) {
return ErrorFactory::createError("Property {$className}::\${$propName} must be a list, non-integer key '{$keyStr}' given");
}

$valueType = $typeNode->genericTypes[0] ?? null;
if ($valueType !== null) {
$context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$key}]" : '[]');

return $registry->validate($value, $valueType, $context);
}
} elseif (\in_array($base, ['array', 'non-empty-array', 'iterable'], true)) {
$genericCount = \count($typeNode->genericTypes);

if ($genericCount >= 2 && $key !== null) {
$keyType = $typeNode->genericTypes[0];
$keyErr = $registry->validate($key, $keyType, "Property {$className}::\${$propName} key");
if ($keyErr !== null) {
return $keyErr;
}
}

$valueType = $genericCount >= 2
? $typeNode->genericTypes[1]
: ($typeNode->genericTypes[0] ?? null);

if ($valueType !== null) {
$context = "Property {$className}::\${$propName}" . ($key !== null ? "['{$keyStr}']" : '[]');

return $registry->validate($value, $valueType, $context);
}
}
} elseif ($typeNode instanceof ArrayTypeNode) {
$context = "Property {$className}::\${$propName}" . ($key !== null ? "[{$keyStr}]" : '[]');

return $registry->validate($value, $typeNode->type, $context);
}
} catch (\Throwable) {
}

return null;
}

/**
* Safely reads the current value of an instance or static property across all visibilities.
*/
Expand Down
37 changes: 34 additions & 3 deletions src/Internal/Checker/ParamChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -944,10 +944,18 @@ private static function inferArrayTemplatesFromAllElements(
?object $thisObj,
array $templates
): void {
if ($typeNode instanceof NullableTypeNode) {
while ($typeNode instanceof NullableTypeNode) {
$typeNode = $typeNode->type;
}

if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) {
foreach ($typeNode->types as $subType) {
self::inferArrayTemplatesFromAllElements($subType, $arrVal, $effectiveFunction, $thisObj, $templates);
}

return;
}

if ($typeNode instanceof GenericTypeNode) {
$baseType = strtolower((string) $typeNode->type);
if (! isset(self::ITERABLE_TYPES[$baseType])) {
Expand Down Expand Up @@ -1109,22 +1117,45 @@ private static function inferGenericObjectNode(
array $templates,
array $classTemplates = []
): void {
if ($typeNode instanceof NullableTypeNode) {
while ($typeNode instanceof NullableTypeNode) {
$typeNode = $typeNode->type;
}

if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) {
foreach ($typeNode->types as $subType) {
self::inferGenericObjectNode($subType, $value, $effectiveFunction, $thisObj, $templates, $classTemplates);
}

return;
}

if ($typeNode instanceof GenericTypeNode && \is_object($value)) {
$baseName = strtolower((string) $typeNode->type);
if (isset(self::COLLECTION_TYPES[$baseName])) {
return;
}

$contextRef = null;
if (str_contains($effectiveFunction, '::')) {
$declaringClass = explode('::', $effectiveFunction, 2)[0];
if (class_exists($declaringClass, false) || class_exists($declaringClass) || interface_exists($declaringClass) || trait_exists($declaringClass)) {
$contextRef = new \ReflectionClass($declaringClass);
}
} elseif (\function_exists($effectiveFunction)) {
$contextRef = new \ReflectionFunction($effectiveFunction);
}

$targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, $contextRef ?? new \ReflectionClass($value));

if (! is_a($value, $targetClassFqcn)) {
return;
}

$boundOnInstance = TemplateManager::getBoundTemplatesForInstance($value);
if ($boundOnInstance === []) {
return;
}

$targetClassFqcn = SpecialTypeResolver::resolveFqcn((string) $typeNode->type, new \ReflectionClass($value));
$targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null;

if ($targetTemplateNames === null) {
Expand Down
26 changes: 24 additions & 2 deletions src/Internal/Generics/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -1324,6 +1324,24 @@ private static function collectInheritedGenericTagBindings(
$normalizedGenericTypes = self::normalizeGenericArguments($genericTypeNode->genericTypes, $parentTemplateNodes);
$hierAliases = DocblockParser::parseClassAliases($hierClass->getName());

$hierTemplates = DocblockParser::parseClassTemplates($hierClass->getName());
if ($hierTemplates === []) {
$hierDoc = StubManager::getClassDoc($hierClass->getName()) ?? $hierClass->getDocComment();
if ($hierDoc !== false) {
$hierPhpDocNode = DocblockExtractor::parseDocString($hierDoc);
$hierTemplates = DocblockExtractor::extractTemplates($hierPhpDocNode);
}
}

$hierFallbackBindings = [];
foreach ($hierTemplates as $tName => $tTag) {
$boundOrDef = $tTag->default ?? $tTag->bound;
if ($boundOrDef !== null) {
$boundOrDef = SpecialTypeResolver::resolve($boundOrDef, $hierClass);
}
$hierFallbackBindings[$tName] = $boundOrDef ?? new IdentifierTypeNode('mixed');
}

foreach ($parentTemplateNames as $idx => $templateName) {
if (isset($normalizedGenericTypes[$idx])) {
$typeArg = $normalizedGenericTypes[$idx];
Expand All @@ -1345,11 +1363,11 @@ private static function collectInheritedGenericTagBindings(
$isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($resolved->name);
$isRealType = self::isRealTypeSymbol($resolved->name);

if (! $isBuiltIn && ! $isRealType) {
if (! $isBuiltIn && ! $isRealType && ! isset($declaredTemplateNames[$resolved->name])) {
continue;
}

if (isset($declaredTemplateNames[$resolved->name])) {
if (isset($declaredTemplateNames[$resolved->name]) && $resolved->name === $templateName) {
continue;
}
}
Expand All @@ -1359,6 +1377,10 @@ private static function collectInheritedGenericTagBindings(
}
}

if (DocblockParser::typeReferencesTemplate($resolved, $declaredTemplateNames) && $hierFallbackBindings !== []) {
$resolved = TemplateSubstitutor::substitute($resolved, $hierFallbackBindings);
}

$bindings[$templateName] ??= $resolved;
}
}
Expand Down
63 changes: 62 additions & 1 deletion src/Internal/Wrapper/IterableWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use TypePHP\Exception\TypeError as TypePHPTypeError;
use TypePHP\Internal\Checker\ConditionalChecker;
use TypePHP\Internal\Diagnostic\ErrorFactory;
Expand Down Expand Up @@ -86,7 +87,7 @@ public static function wrap(string $function, string $paramName, mixed $iterable

[$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $aliases);

if ($keyTypeNode === null && $itemTypeNode === null) {
if (self::isUnconstrainedKey($keyTypeNode) && self::isUnconstrained($itemTypeNode)) {
return $iterable;
}

Expand All @@ -106,6 +107,53 @@ public static function wrap(string $function, string $paramName, mixed $iterable
return self::wrapGenerator($iterable, $typeCheckCallback);
}

/**
* Checks if a key type node is absent or covers all possible collection keys (mixed, array-key, or any scalar/object).
*/
private static function isUnconstrainedKey(?TypeNode $node): bool
{
if ($node === null) {
return true;
}

if ($node instanceof IdentifierTypeNode) {
$lower = strtolower($node->name);

return \in_array($lower, ['mixed', 'array-key'], true);
}

if ($node instanceof UnionTypeNode) {
$types = [];
foreach ($node->types as $t) {
if ($t instanceof IdentifierTypeNode) {
$types[strtolower($t->name)] = true;
}
}

if (isset($types['mixed']) || isset($types['array-key'])) {
return true;
}

if (isset($types['string'], $types['int'], $types['bool'], $types['float'], $types['object'])) {
return true;
}
}

return false;
}

/**
* Checks if a type node is absent or unconstrained mixed.
*/
private static function isUnconstrained(?TypeNode $node): bool
{
if ($node === null) {
return true;
}

return $node instanceof IdentifierTypeNode && strtolower($node->name) === 'mixed';
}

/**
* Extracts key and value TypeNodes from an iterable type node AST or type alias.
*
Expand Down Expand Up @@ -190,6 +238,7 @@ private static function createValidationCallback(

/**
* Wraps an iterable generator in an interceptor generator to evaluate type checks on each yield.
* Advances generators using valid()/current()/next() without calling rewind() on already-started generators.
*
* @param iterable<mixed, mixed> $iterable
* @param \Closure(mixed, mixed): void $typeCheckCallback
Expand All @@ -198,6 +247,18 @@ private static function createValidationCallback(
*/
private static function wrapGenerator(iterable $iterable, \Closure $typeCheckCallback): Generator
{
if ($iterable instanceof Generator) {
while ($iterable->valid()) {
$key = $iterable->key();
$value = $iterable->current();
$typeCheckCallback($key, $value);
yield $key => $value;
$iterable->next();
}

return;
}

foreach ($iterable as $key => $value) {
$typeCheckCallback($key, $value);
yield $key => $value;
Expand Down
Loading
Loading