Skip to content

Commit

Permalink
restrictReturnTypes configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
jack-worman committed Dec 24, 2022
1 parent 8b05f2e commit f9e9aad
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
57 changes: 57 additions & 0 deletions docs/running_psalm/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,63 @@ Arrays bigger than this value (100 by default) will be transformed in a generic

Please note that changing this setting might introduce unwanted side effects and those side effects won't be considered as bugs.

#### restrictReturnTypes

```xml
<psalm
restrictReturnTypes="true"
>
```

Emits `LessSpecificReturnType` when the declared return type is not as tight as
the inferred return type.

This code:
```php
function getOne(): int // declared type: int
{
return 1; // inferred type: 1 (int literal)
}
```
Will give this error: `LessSpecificReturnType - The inferred return type '1' for
a is more specific than the declared return type 'int'`

To fix the error, you should specify the more specific type in the doc-block:
```php
/**
* @return 1
*/
function getOne(): int
{
return 1;
}
```

**Warning**: Forcing a tighter type is not always the best course of action and
may cause unexpected results. The following code is invalid with
`restrictReturnTypes="true"`:
```php
class StandardCar {
/**
* @return list{'motor', 'brakes', 'wheels'}
*/
public function getSystems(): array {
return ['motor', 'brakes', 'wheels'];
}
}

class PremiumCar extends StandardCar {
/**
* @return list{'motor', 'brakes', 'wheels', 'rear parking sensor'}
*/
public function getSystems(): array {
return ['motor', 'brakes', 'wheels', 'rear parking sensor'];
}
}
```
`ImplementedReturnTypeMismatch - The inherited return type 'list{'motor', 'brakes', 'wheels'}' for StandardCar::getSystems is different to the implemented return type for PremiumCar::getsystems 'list{'motor', 'brakes', 'wheels', 'rear parking sensor'}'`


## Project settings

#### &lt;projectFiles&gt;
Expand Down
5 changes: 0 additions & 5 deletions psalm.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,11 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
name="Psalm for Psalm"
useDocblockTypes="true"
errorLevel="1"
strictBinaryOperands="false"
rememberPropertyAssignmentsAfterCall="true"
checkForThrowsDocblock="false"
throwExceptionOnError="0"
findUnusedCode="true"
ensureArrayStringOffsetsExist="true"
ensureArrayIntOffsetsExist="true"
resolveFromConfigFile="true"
xsi:schemaLocation="https://getpsalm.org/schema/config config.xsd"
limitMethodComplexity="true"
errorBaseline="psalm-baseline.xml"
Expand Down

0 comments on commit f9e9aad

Please sign in to comment.