Skip to content

Commit

Permalink
Constructor with default paramater array does not work
Browse files Browse the repository at this point in the history
  • Loading branch information
Korbeil committed Jul 29, 2024
1 parent 4ba0372 commit 32a6689
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/Generator/CreateTargetStatementsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ private function constructorArgument(GeneratorMetadata $metadata, PropertyMetada
$defaultValueExpr = new Expr\ConstFetch(new Name('null'));
}

if ($defaultValueExpr instanceof Expr\Array_) {
// $constructarg_3 = count($values) > 0 ? $values : array();
$argumentAssignedValue = new Expr\Ternary(new Expr\BinaryOp\Greater(new Expr\FuncCall(new Name('count'), [new Arg($output)]), create_scalar_int(0)), $output, $defaultValueExpr);
} else {
// $constructarg_0 = $values ?? array();
$argumentAssignedValue = new Expr\BinaryOp\Coalesce($output, $defaultValueExpr);
}

return [
new Stmt\If_(new Expr\StaticCall(new Name\FullyQualified(MapperContext::class), 'hasConstructorArgument', [
new Arg($variableRegistry->getContext()),
Expand All @@ -221,7 +229,7 @@ private function constructorArgument(GeneratorMetadata $metadata, PropertyMetada
],
'else' => new Stmt\Else_([
...$propStatements,
new Stmt\Expression(new Expr\Assign($constructVar, new Expr\BinaryOp\Coalesce($output, $defaultValueExpr))),
new Stmt\Expression(new Expr\Assign($constructVar, $argumentAssignedValue)),
]),
]),
new Arg($constructVar, name: new Identifier($parameter->getName())),
Expand Down
2 changes: 1 addition & 1 deletion src/Transformer/AbstractArrayTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function transform(Expr $input, Expr $target, PropertyMetadata $propertyM
$itemStatements[] = new Stmt\Expression($this->getAssignExpr($valuesVar, $output, $loopKeyVar, $assignByRef));
}

$statements[] = new Stmt\Foreach_($input, $loopValueVar, [
$statements[] = new Stmt\Foreach_(new Expr\BinaryOp\Coalesce($input, new Expr\Array_()), $loopValueVar, [
'stmts' => $itemStatements,
'keyVar' => $loopKeyVar,
]);
Expand Down
3 changes: 2 additions & 1 deletion tests/Fixtures/ConstructorWithDefaultValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
public function __construct(
public string $baz,
public ?int $foo = 1,
public int $bar = 0
public int $bar = 0,
public array $someOtters = [],
) {
}
}

0 comments on commit 32a6689

Please sign in to comment.