From f9e9aad990d63043a06f26ed39f447df9d30b36f Mon Sep 17 00:00:00 2001 From: Jack Worman Date: Sat, 24 Dec 2022 08:57:00 -0600 Subject: [PATCH] restrictReturnTypes configuration --- docs/running_psalm/configuration.md | 57 +++++++++++++++++++++++++++++ psalm.xml.dist | 5 --- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/docs/running_psalm/configuration.md b/docs/running_psalm/configuration.md index a6d60528d..8b8d5a385 100644 --- a/docs/running_psalm/configuration.md +++ b/docs/running_psalm/configuration.md @@ -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 + +``` + +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 #### <projectFiles> diff --git a/psalm.xml.dist b/psalm.xml.dist index 90d2c8382..f81ee56d4 100644 --- a/psalm.xml.dist +++ b/psalm.xml.dist @@ -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"