1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-26 20:34:47 +01:00

Fix issue assigning string-typed properties without a string cast

This commit is contained in:
Matt Brown 2018-01-02 18:01:59 -05:00
parent 310f91ea81
commit e6aae2f2e2
3 changed files with 42 additions and 2 deletions

View File

@ -18,6 +18,7 @@ use Psalm\Exception\DocblockParseException;
use Psalm\Exception\IncorrectDocblockException;
use Psalm\Issue\AssignmentToVoid;
use Psalm\Issue\DeprecatedProperty;
use Psalm\Issue\ImplicitToStringCast;
use Psalm\Issue\InvalidDocblock;
use Psalm\Issue\InvalidPropertyAssignment;
use Psalm\Issue\InvalidScope;
@ -904,13 +905,35 @@ class AssignmentChecker
$project_checker,
$assignment_value_type,
$class_property_type,
$assignment_value_type->ignore_nullable_issues
$assignment_value_type->ignore_nullable_issues,
false,
$has_scalar_match,
$type_coerced,
$type_coerced_from_mixed,
$to_string_cast
)) {
$invalid_assignment_value_types[] = [
(string)$class_property_type,
(string)$assignment_value_type,
];
} else {
if ($to_string_cast) {
if (IssueBuffer::accepts(
new ImplicitToStringCast(
$var_id . ' expects \'' . $class_property_type . '\', '
. $assignment_value_type . ' provided with a __toString method',
new CodeLocation(
$statements_checker->getSource(),
$assignment_value ?: $stmt,
$context->include_location
)
),
$statements_checker->getSuppressedIssues()
)) {
// fall through
}
}
$has_valid_assignment_value_type = true;
}
}

View File

@ -86,7 +86,7 @@ class TypeChecker
$type_match_found = true;
}
if ($atomic_to_string_cast !== true) {
if ($atomic_to_string_cast !== true && $type_match_found) {
$all_to_string_cast = false;
}
}

View File

@ -1051,6 +1051,23 @@ class PropertyTypeTest extends TestCase
echo $x->$y;',
'error_message' => 'UndefinedGlobalVariable',
],
'toStringPropertyAssignment' => [
'<?php
class A {
/** @var ?string */
public $foo;
}
class B {
public function __toString() {
return "bar";
}
}
$a = new A();
$a->foo = new B;',
'error_message' => 'ImplicitToStringCast',
],
];
}
}