Skip to content

Commit

Permalink
Fix promoted default values (#672)
Browse files Browse the repository at this point in the history
* Fix FieldsBuilder ignoring promoted properties' default values

* Add test for promoted default value

* Fix code style

* Fix code style
  • Loading branch information
oprypkhantc authored Apr 1, 2024
1 parent 59048a1 commit 02c6131
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/FieldsBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public function getInputFields(string $className, string $inputName, bool $isUpd
$reflectorByFields = [];

$inputFields = [];
$defaultProperties = $refClass->getDefaultProperties();
$defaultProperties = $this->getClassDefaultProperties($refClass);

$closestMatchingTypeClass = null;
$parent = get_parent_class($refClass->getName());
Expand Down Expand Up @@ -1143,4 +1143,20 @@ private function getClassConstructParameterNames(ReflectionClass $refClass): arr

return $names;
}

/** @return array<string, mixed> */
private function getClassDefaultProperties(ReflectionClass $refClass): array
{
$properties = $refClass->getDefaultProperties();

foreach ($refClass->getConstructor()?->getParameters() ?? [] as $parameter) {
if (! $parameter->isPromoted() || ! $parameter->isDefaultValueAvailable()) {
continue;
}

$properties[$parameter->getName()] = $parameter->getDefaultValue();
}

return $properties;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public function updateArticle(UpdateArticleInput $input): Article
{
$article = new Article('test');
$article->magazine = $input->magazine;
$article->summary = $input->summary;

return $article;
}
Expand Down
1 change: 1 addition & 0 deletions tests/Fixtures/Integration/Models/UpdateArticleInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public function __construct(
#[Field]
#[Security("magazine != 'NYTimes'")]
public readonly string|null $magazine,
public readonly string $summary = 'default',
)
{
}
Expand Down
2 changes: 2 additions & 0 deletions tests/Integration/EndToEndTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1911,6 +1911,7 @@ public function testEndToEndInputConstructor(): void
magazine: "Test"
}) {
magazine
summary
}
}
';
Expand All @@ -1922,6 +1923,7 @@ public function testEndToEndInputConstructor(): void

$data = $this->getSuccessResult($result);
$this->assertSame('Test', $data['updateArticle']['magazine']);
$this->assertSame('default', $data['updateArticle']['summary']);
$queryString = '
mutation {
updateArticle(input: {
Expand Down

0 comments on commit 02c6131

Please sign in to comment.