Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "typephp/typephp",
"description": "Transparent Runtime type checker for PHP. Enforces PHPDoc annotations including generics, typed arrays, array shapes, and advanced types at runtime in development and production.",
"description": "Transparent Runtime type checker for PHP. Enforces PHPDoc annotations including generics, typed arrays, array shapes, and advanced types at runtime.",
"type": "library",
"license": "MIT",
"keywords": [
Expand Down
128 changes: 123 additions & 5 deletions src/Internal/Checker/ParamChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,20 @@ private static function validateAllParameters(
}
}

if (\count($allTemplates) > 1) {
return self::validateCrossReferencedTemplateBounds(
$contractTypes,
$baseTypes,
$vars,
$effectiveFunction,
$thisObj,
$allTemplates,
$registry,
$thisOrClass,
$sensitiveParams
);
}

return null;
}

Expand Down Expand Up @@ -636,6 +650,87 @@ private static function extractCallableNodes(array $types): array
return $callableNodes;
}

/**
* Re-validates template upper bounds that reference other sibling templates once all parameters have been bound.
*
* @param array<string, TypeNode> $contractTypes
* @param array<string, TypeNode> $baseTypes
* @param array<string, mixed> $vars
* @param array<string, TemplateTagValueNode> $allTemplates
* @param array<string, bool> $sensitiveParams
*/
private static function validateCrossReferencedTemplateBounds(
array $contractTypes,
array $baseTypes,
array $vars,
string $effectiveFunction,
?object $thisObj,
array $allTemplates,
TypeValidatorRegistry $registry,
object|string|null $thisOrClass = null,
array $sensitiveParams = []
): ?ErrorMessage {
$finalBoundTemplates = TemplateManager::getBoundTemplates($effectiveFunction, $thisOrClass, $allTemplates);
if (\count($finalBoundTemplates) === 0) {
return null;
}

foreach ($allTemplates as $tName => $templateNode) {
if ($templateNode->bound === null || ! isset($finalBoundTemplates[$tName])) {
continue;
}

$otherTemplates = $allTemplates;
unset($otherTemplates[$tName]);

if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $otherTemplates)) {
continue;
}

$substitutedBound = TemplateSubstitutor::substitute($templateNode->bound, $finalBoundTemplates);
$resolvedBound = SpecialTypeResolver::resolve($substitutedBound, $effectiveFunction, $thisObj);

$matchedParam = false;
foreach ($contractTypes as $paramName => $_) {
if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) {
continue;
}

$baseType = $baseTypes[$paramName];
$val = $vars[$paramName];
$isSensitive = $sensitiveParams[$paramName] ?? false;

if ($baseType instanceof GenericTypeNode && self::isClassStringTemplate($baseType, [$tName => $templateNode])) {
$matchedParam = true;
if (\is_string($val) && ! self::checkClassStringSatisfiesBound($val, $resolvedBound)) {
$redact = $isSensitive || Config::isRedactValuesEnabled();
$boundDisplay = (string) $resolvedBound;
$displayVal = $redact ? 'string given' : "'" . $val . "' given";

return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . ' (class-string<' . $tName . '>) must be a class-string of ' . $boundDisplay . ', ' . $displayVal);
}
} elseif (self::getTemplateName($baseType, [$tName => $templateNode]) === $tName) {
$matchedParam = true;
$sampleVal = ($baseType instanceof ArrayTypeNode && \is_array($val)) ? ($val[0] ?? null) : $val;
if ($sampleVal !== null) {
$err = $registry->validate($sampleVal, $resolvedBound, $effectiveFunction . '(): Argument $' . $paramName . ' (template ' . $tName . ')', $isSensitive);
if ($err !== null) {
return $err;
}
}
}
}

if (! $matchedParam && ! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) {
return ErrorFactory::createError(
$effectiveFunction . "(): Generic type argument {$finalBoundTemplates[$tName]} does not satisfy upper bound {$resolvedBound} of template {$tName}"
);
}
}

return null;
}

/**
* Extracts an inferred TypeNode from a closure parameter, ignoring `mixed`.
*/
Expand Down Expand Up @@ -1311,7 +1406,19 @@ private static function resolveClassStringTemplate(
if ($templateNode->bound !== null) {
$boundLower = $templateNode->bound instanceof IdentifierTypeNode ? strtolower($templateNode->bound->name) : '';
if ($boundLower !== 'object' && $boundLower !== 'mixed') {
$resolvedBound = SpecialTypeResolver::resolve($templateNode->bound, $function, $thisObj);
$boundNode = $templateNode->bound;
$classNode = TemplateManager::$classNodeCache[$val] ??= new IdentifierTypeNode($val);
$currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates);
$allBindings = [...$currentBindings, $templateName => $classNode];

if (
TemplateManager::isFBounded($templateNode, $function)
|| DocblockParser::typeReferencesTemplate($boundNode, $templates)
) {
$boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings);
}

$resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj);
if (! self::checkClassStringSatisfiesBound($val, $resolvedBound)) {
$boundDisplay = (string) $resolvedBound;
$displayVal = $redact ? 'string given' : "'" . $val . "' given";
Expand Down Expand Up @@ -1455,7 +1562,8 @@ private static function resolveTemplateParam(
$templateNode,
$isVariadic,
$isClassLevelTemplate,
$registry
$registry,
$templates
);
}

Expand All @@ -1473,6 +1581,9 @@ private static function resolveTemplateParam(
);
}

/**
* @param array<string, TemplateTagValueNode> $templates
*/
private static function bindInitialTemplate(
mixed $val,
string $paramName,
Expand All @@ -1483,15 +1594,22 @@ private static function bindInitialTemplate(
TemplateTagValueNode $templateNode,
bool $isVariadic,
bool $isClassLevelTemplate,
TypeValidatorRegistry $registry
TypeValidatorRegistry $registry,
array $templates = []
): ?ErrorMessage {
$sampleVal = ($isVariadic && \is_array($val)) ? ($val[0] ?? null) : $val;
$inferredType = TemplateManager::inferTypeFromValue($sampleVal);

if ($templateNode->bound !== null) {
$boundNode = $templateNode->bound;
if (TemplateManager::isFBounded($templateNode, $function)) {
$boundNode = TemplateSubstitutor::substitute($boundNode, [$templateName => $inferredType]);
$currentBindings = TemplateManager::getBoundTemplates($function, $thisObj, $templates);
$allBindings = [...$currentBindings, $templateName => $inferredType];

if (
TemplateManager::isFBounded($templateNode, $function)
|| DocblockParser::typeReferencesTemplate($boundNode, $templates)
) {
$boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings);
}

$resolvedBound = SpecialTypeResolver::resolve($boundNode, $function, $thisObj);
Expand Down
57 changes: 50 additions & 7 deletions src/Internal/Generics/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -887,12 +887,33 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t
$templateList = array_values($templates);
$normalizedTypeArgs = self::normalizeGenericArguments($typeNode->genericTypes, $templateList);

$candidateBindings = self::$instanceTemplateBindings[$instance] ?? [];
foreach ($templateList as $index => $templateTag) {
if (isset($normalizedTypeArgs[$index])) {
$arg = $normalizedTypeArgs[$index];
$isWildcardOrMixed = ($arg instanceof IdentifierTypeNode && ($arg->name === '*' || strtolower($arg->name) === 'mixed'));
if (! $isWildcardOrMixed) {
$candidateBindings[$templateTag->name] = $arg;
}
}
}

foreach ($templateList as $index => $templateTag) {
if (! isset($normalizedTypeArgs[$index])) {
continue;
}

$err = self::bindSingleTemplateArgument($instance, $className, $normalizedTypeArgs[$index], $typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT, $templateTag, $classVariances, $context, $forceBind);
$err = self::bindSingleTemplateArgument(
$instance,
$className,
$normalizedTypeArgs[$index],
$typeNode->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT,
$templateTag,
$classVariances,
$context,
$forceBind,
$candidateBindings
);
if ($err !== null) {
return $err;
}
Expand Down Expand Up @@ -959,6 +980,7 @@ private static function collectHierarchyTemplatesAndVariances(\ReflectionClass $

/**
* @param array<string, string> $classVariances
* @param array<string, TypeNode> $candidateBindings
*/
private static function bindSingleTemplateArgument(
object $instance,
Expand All @@ -968,7 +990,8 @@ private static function bindSingleTemplateArgument(
TemplateTagValueNode $templateTag,
array $classVariances,
string $context,
bool $forceBind
bool $forceBind,
array $candidateBindings = []
): ?ErrorMessage {
if ($expectedTypeNode instanceof IdentifierTypeNode) {
if (str_contains($expectedTypeNode->name, '::')) {
Expand All @@ -994,8 +1017,9 @@ private static function bindSingleTemplateArgument(

if ($templateTag->bound !== null && ! $isWildcardOrMixed) {
$boundNode = $templateTag->bound;
if (self::isFBounded($templateTag, $className)) {
$boundNode = TemplateSubstitutor::substitute($boundNode, [$templateTag->name => $expectedTypeNode]);
$allBindings = [...$candidateBindings, $templateTag->name => $expectedTypeNode];
if (self::isFBounded($templateTag, $className) || DocblockParser::typeReferencesTemplate($boundNode, $allBindings)) {
$boundNode = TemplateSubstitutor::substitute($boundNode, $allBindings);
}

$satisfiesBound = self::checkVariance($expectedTypeNode, $boundNode, GenericTypeNode::VARIANCE_COVARIANT);
Expand Down Expand Up @@ -1234,7 +1258,7 @@ private static function collectInheritedGenericTagBindings(
}
}

$bindings[$templateName] = $resolved;
$bindings[$templateName] ??= $resolved;
}
}
} catch (\Throwable $e) {
Expand Down Expand Up @@ -1423,13 +1447,24 @@ private static function checkIdentifierAgainstGenericVariance(
$actualArg = $classBindings[$tName];
$expectedArg = $expected->genericTypes[$idx];

if ($expectedArg instanceof IdentifierTypeNode) {
$isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedArg->name);
$isRealType = self::isRealTypeSymbol($expectedArg->name);
if (! $isBuiltIn && ! $isRealType) {
continue;
}
}

$useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
$declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
$templateBound = $parentTemplates[$tName]->bound ?? null;
$isExpectedUpperBound = $templateBound !== null && (string) $expectedArg === (string) $templateBound;

$innerVariance = match (true) {
$useSiteVariance !== GenericTypeNode::VARIANCE_INVARIANT => $useSiteVariance,
$declaredVariance === GenericTypeNode::VARIANCE_CONTRAVARIANT => GenericTypeNode::VARIANCE_CONTRAVARIANT,
default => GenericTypeNode::VARIANCE_COVARIANT,
$declaredVariance !== GenericTypeNode::VARIANCE_INVARIANT => $declaredVariance,
$isExpectedUpperBound => GenericTypeNode::VARIANCE_COVARIANT,
default => GenericTypeNode::VARIANCE_INVARIANT,
};

if (! self::checkVariance($actualArg, $expectedArg, $innerVariance)) {
Expand Down Expand Up @@ -1588,6 +1623,14 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge
}

foreach ($expected->genericTypes as $idx => $expectedInner) {
if ($expectedInner instanceof IdentifierTypeNode) {
$isBuiltIn = SpecialTypeResolver::isBuiltInTypeKeyword($expectedInner->name);
$isRealType = self::isRealTypeSymbol($expectedInner->name);
if (! $isBuiltIn && ! $isRealType) {
continue;
}
}

$existingInner = $existing->genericTypes[$idx] ?? new IdentifierTypeNode('mixed');
$useSiteVariance = $expected->variances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
$declaredVariance = $declaredVariances[$idx] ?? GenericTypeNode::VARIANCE_INVARIANT;
Expand Down
2 changes: 1 addition & 1 deletion src/Internal/Util/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public static function isEnabled(): bool
}
}

if (\defined('TYPEPHP_DISABLE') && TYPEPHP_DISABLE) {
if (\defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE) {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
|| (isset($_ENV['TYPEPHP_DISABLE']) && filter_var($_ENV['TYPEPHP_DISABLE'], FILTER_VALIDATE_BOOLEAN))
|| (isset($_SERVER['TYPEPHP_DISABLE']) && filter_var($_SERVER['TYPEPHP_DISABLE'], FILTER_VALIDATE_BOOLEAN))
);
$isDisabledConst = \defined('TYPEPHP_DISABLE') && TYPEPHP_DISABLE;
$isDisabledConst = \defined('TYPEPHP_DISABLE') && (bool) TYPEPHP_DISABLE;

$isTooling = false;
$binary = '';
Expand Down
Loading
Loading