Skip to content

Commit 978c639

Browse files
authored
Allow passing explicit null values for optional input members (#1542)
This makes it easier to define the array literal for input objects as PHP does not have a syntax sugar for conditional keys in an array literal. This is consistent with the generated code for value objects. Even though input objects allow to omit required members in the constructor shape (as they can be set later by using the setter), the phpdoc type still does not allow passing null explicitly (even though the code would deal with it until the validation run) so that static analysis tools can catch mistakes there. Passing a required member explicitly is intended to pass a valid value for it and not a potentially missing one.
1 parent d425dfc commit 978c639

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/Generator/CodeGenerator/TypeGenerator.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,12 @@ public function generateDocblock(StructureShape $shape, ClassName $shapeClassNam
103103
}
104104
}
105105

106-
if ($allNullable || $nullable) {
107-
if ($isObject) {
108-
$body[] = sprintf(' %s?: %s,', $member->getName(), 'null|' . $param);
109-
} else {
110-
$body[] = sprintf(' %s?: %s,', $member->getName(), $param);
111-
}
106+
if ($nullable) {
107+
$body[] = sprintf(' %s?: %s,', $member->getName(), 'null|' . $param);
108+
} elseif ($allNullable) {
109+
// For input objects, the constructor allows to omit all members to set them later. But when provided,
110+
// they should respect the nullability of the member.
111+
$body[] = sprintf(' %s?: %s,', $member->getName(), $param);
112112
} else {
113113
$body[] = sprintf(' %s: %s,', $member->getName(), $param);
114114
}

0 commit comments

Comments
 (0)