Skip to content

Commit

Permalink
Merge pull request #9887 from kkmuffme/readonly-property-ignore-invar…
Browse files Browse the repository at this point in the history
…iance-if-contained

readonly does not have write access, therefore is safe as long as the…
  • Loading branch information
orklah committed Jun 9, 2023
2 parents 99a54fb + 0a54c84 commit 5df772b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Psalm/Internal/Analyzer/ClassAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
) {
Expand Down
17 changes: 17 additions & 0 deletions tests/PropertyTypeInvarianceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,23 @@ class Baz extends Bar {
public $d;
}',
],
'allowReadonly' => [
'code' => '<?php
class ParentClass
{
/**
* @readonly
* @var null|string
*/
protected $mightExist;
}
class ChildClass extends ParentClass
{
/** @var string */
protected $mightExist = "";
}',
],
];
}

Expand Down

0 comments on commit 5df772b

Please sign in to comment.