From 0a54c84055b1dc47852f76f6452ef174d09e5bcd Mon Sep 17 00:00:00 2001 From: kkmuffme <11071985+kkmuffme@users.noreply.github.com> Date: Fri, 9 Jun 2023 12:37:41 +0200 Subject: [PATCH] readonly does not have write access, therefore is safe as long as the type is contained in the parent type Fix https://github.com/vimeo/psalm/issues/9831#issuecomment-1569022701 --- src/Psalm/Internal/Analyzer/ClassAnalyzer.php | 15 ++++++++++++++- tests/PropertyTypeInvarianceTest.php | 17 +++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/Psalm/Internal/Analyzer/ClassAnalyzer.php b/src/Psalm/Internal/Analyzer/ClassAnalyzer.php index fb72507a305..84d33115fd5 100644 --- a/src/Psalm/Internal/Analyzer/ClassAnalyzer.php +++ b/src/Psalm/Internal/Analyzer/ClassAnalyzer.php @@ -802,7 +802,20 @@ public static function addContextProperties( $codebase, ); - if ($property_storage->location + if ($guide_property_storage->readonly + && UnionTypeComparator::isContainedBy( + $codebase, + $property_type, + $guide_property_type, + false, + false, + null, + false, + false, + )) { + // if the original property is readonly, it cannot be written + // therefore invariance is not a problem, if the parent type contains the child type + } elseif ($property_storage->location && !$property_type->equals($guide_property_type, false) && $guide_class_storage->user_defined ) { diff --git a/tests/PropertyTypeInvarianceTest.php b/tests/PropertyTypeInvarianceTest.php index fdf00095bab..ba4b8a7b11b 100644 --- a/tests/PropertyTypeInvarianceTest.php +++ b/tests/PropertyTypeInvarianceTest.php @@ -231,6 +231,23 @@ class Baz extends Bar { public $d; }', ], + 'allowReadonly' => [ + 'code' => '