mirror of
https://github.com/danog/psalm.git
synced 2024-11-26 20:34:47 +01:00
Allow mutation-free method calls in pure functions
This commit is contained in:
parent
dee2cf3281
commit
0279c6f6d9
@ -1205,10 +1205,13 @@ class MethodCallAnalyzer extends \Psalm\Internal\Analyzer\Statements\Expression\
|
||||
&& (!empty($stmt->var->inferredType->external_mutation_free)
|
||||
|| isset($stmt->var->pure));
|
||||
|
||||
if ($context->pure && !$method_storage->pure && !$method_pure_compatible) {
|
||||
if ($context->pure
|
||||
&& !$method_storage->mutation_free
|
||||
&& !$method_pure_compatible
|
||||
) {
|
||||
if (IssueBuffer::accepts(
|
||||
new ImpureMethodCall(
|
||||
'Cannot call an impure method ' . $method_id . ' from a pure context',
|
||||
'Cannot call an mutation-free method ' . $method_id . ' from a pure context',
|
||||
new CodeLocation($source, $stmt->name)
|
||||
),
|
||||
$statements_analyzer->getSuppressedIssues()
|
||||
|
@ -58,6 +58,41 @@ class ImmutableAnnotationTest extends TestCase
|
||||
}
|
||||
}',
|
||||
],
|
||||
'addToCart' => [
|
||||
'<?php
|
||||
/** @psalm-immutable */
|
||||
class Cart {
|
||||
/** @var CartItem[] */
|
||||
public array $items;
|
||||
|
||||
/** @param CartItem[] $items */
|
||||
public function __construct(array $items) {
|
||||
$this->items = $items;
|
||||
}
|
||||
|
||||
public function addItem(CartItem $item) : self {
|
||||
$items = $this->items;
|
||||
$items[] = $item;
|
||||
return new Cart($items);
|
||||
}
|
||||
}
|
||||
|
||||
/** @psalm-immutable */
|
||||
class CartItem {
|
||||
public string $name;
|
||||
public float $price;
|
||||
|
||||
public function __construct(string $name, float $price) {
|
||||
$this->name = $name;
|
||||
$this->price = $price;
|
||||
}
|
||||
}
|
||||
|
||||
/** @psalm-pure */
|
||||
function addItemToCart(Cart $c, string $name, float $price) : Cart {
|
||||
return $c->addItem(new CartItem($name, $price));
|
||||
}',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user