Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PossiblyNullArgument: Adding common problem cases and possible solutions #8135

Merged
merged 4 commits into from Jun 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 39 additions & 1 deletion docs/running_psalm/issues/PossiblyNullArgument.md
Expand Up @@ -5,6 +5,44 @@ Emitted when calling a function with a value that’s possibly null when the fun
```php
<?php

function foo(string $s) : void {}
function foo(string $s): void {}
foo(rand(0, 1) ? "hello" : null);
```

## Common Problem Cases

### Using a Function Call inside `if`

```php
if (is_string($cat->getName()) {
foo($cat->getName());
}
```
This fails since it's not guaranteed that subsequent calls to `$cat->getName()` always give the same result.

#### Possible Solutions

* Use a variable:
```php
$catName = $cat->getName();
if (is_string($catName) {
foo($catName);
}
unset($catName);
```
* Add [`@psalm-mutation-free`](../../annotating_code/supported_annotations.md#psalm-mutation-free) to the declaration of the function

### Calling Another Function After `if`

```php
if (is_string($cat->getName()) {
changeCat();
foo($cat->getName());
}
```
This fails since psalm cannot know if `changeCat()` does actually modify `$cat`.

#### Possible Solutions

* Add [`@psalm-mutation-free`](../../annotating_code/supported_annotations.md#psalm-mutation-free) to the declaration of the other function (here: `changeCat()`) too
* Use a variable: See above