From a50faac032b76ef6ebe5c096886e1b91067e8ded Mon Sep 17 00:00:00 2001 From: Melech Mizrachi Date: Thu, 22 Feb 2024 11:18:13 -0700 Subject: [PATCH] Fix a false flag issue with InvalidConstantAssignmentValue being thrown for constants over a certain length. Usually happens with arrays. Check if this type was defined via a dockblock or type hint otherwise the inferred type should always match the assigned type, and we don't even need to do additional checks There is an issue with constants over a certain length where additional values are added to fallback_params in the assigned_type but not in const_storage_type which causes a false flag for this error to appear. Usually happens with arrays --- .../Statements/Expression/ClassConstAnalyzer.php | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Psalm/Internal/Analyzer/Statements/Expression/ClassConstAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Expression/ClassConstAnalyzer.php index 92025d0bb2f..41c04ed79c0 100644 --- a/src/Psalm/Internal/Analyzer/Statements/Expression/ClassConstAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/Statements/Expression/ClassConstAnalyzer.php @@ -721,19 +721,27 @@ public static function analyzeAssignment( // Check assigned type matches docblock type if ($assigned_type = $statements_analyzer->node_data->getType($const->value)) { - if ($const_storage->type !== null + $const_storage_type = $const_storage->type; + + if ($const_storage_type !== null && $const_storage->stmt_location !== null - && $assigned_type !== $const_storage->type + && $assigned_type !== $const_storage_type + // Check if this type was defined via a dockblock or type hint otherwise the inferred type + // should always match the assigned type and we don't even need to do additional checks + // There is an issue with constants over a certain length where additional values + // are added to fallback_params in the assigned_type but not in const_storage_type + // which causes a false flag for this error to appear. Usually happens with arrays + && ($const_storage_type->from_docblock || $const_storage_type->from_property) && !UnionTypeComparator::isContainedBy( $statements_analyzer->getCodebase(), $assigned_type, - $const_storage->type, + $const_storage_type, ) ) { IssueBuffer::maybeAdd( new InvalidConstantAssignmentValue( "{$class_storage->name}::{$const->name->name} with declared type " - . "{$const_storage->type->getId()} cannot be assigned type {$assigned_type->getId()}", + . "{$const_storage_type->getId()} cannot be assigned type {$assigned_type->getId()}", $const_storage->stmt_location, "{$class_storage->name}::{$const->name->name}", ),