Skip to content

Commit 5a0df94

Browse files
authored
Account for optional keys in get_flag_value() return type (#368)
1 parent ce989aa commit 5a0df94

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

‎src/PHPStan/GetFlagValueFunctionDynamicReturnTypeExtension.php‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,22 +61,28 @@ public function getTypeFromFunctionCall(
6161
$keyTypes = $assocArgsConstantArray->getKeyTypes();
6262
$valueTypes = $assocArgsConstantArray->getValueTypes();
6363
$resolvedValueType = null;
64+
$isOptionalKey = false;
6465

6566
foreach ( $keyTypes as $index => $keyType ) {
6667
$keyConstantStrings = $keyType->getConstantStrings();
6768
if ( count( $keyConstantStrings ) === 1 && $keyConstantStrings[0]->getValue() === $flagValue ) {
6869
$resolvedValueType = $valueTypes[ $index ];
70+
$isOptionalKey = $assocArgsConstantArray->isOptionalKey( $index );
6971
break;
7072
}
7173
}
7274

73-
if ( null !== $resolvedValueType ) {
74-
// Key definitely exists and has a resolved type.
75-
return $resolvedValueType;
76-
} else {
75+
if ( null === $resolvedValueType ) {
7776
// Key definitely does not exist in this constant array.
7877
return $defaultType;
7978
}
79+
80+
// get_flag_value() uses isset(), so a null value also falls back to the default.
81+
if ( $resolvedValueType->isNull()->no() && ! $isOptionalKey ) {
82+
return $resolvedValueType;
83+
}
84+
85+
return TypeCombinator::union( TypeCombinator::removeNull( $resolvedValueType ), $defaultType );
8086
}
8187

8288
// 4.b. $assoc_args is not a single ConstantArray (but $flagValue is known):

‎tests/data/get_flag_value.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,14 @@
6060

6161
$value = get_flag_value( $assoc_args, $key2, 123 );
6262
assertType( "123|'bar'|true", $value );
63+
64+
/**
65+
* @param array{foo?: string, bar?: 'json'|'xml', baz: bool, qux: string|null} $assoc_args
66+
*/
67+
function test_shape_with_optional_keys( array $assoc_args ): void {
68+
assertType( 'string|null', get_flag_value( $assoc_args, 'foo' ) );
69+
assertType( "'json'|'xml'|null", get_flag_value( $assoc_args, 'bar' ) );
70+
assertType( "'json'|'xml'|false", get_flag_value( $assoc_args, 'bar', false ) );
71+
assertType( 'bool', get_flag_value( $assoc_args, 'baz', 123 ) );
72+
assertType( '123|string', get_flag_value( $assoc_args, 'qux', 123 ) );
73+
}

0 commit comments

Comments
 (0)