Skip to content

Commit

Permalink
#126: Refactor extract method generation to private method
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Riley committed May 25, 2023
1 parent e38b93c commit c202991
Showing 1 changed file with 23 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,28 @@ private function generatePropertyHydrateCall(ObjectProperty $property, string $i
];
}

/**
* @return string[]
*
* @psalm-return list<string>
*/
private function generatePropertyExtractCall(ObjectProperty $property): array
{
$propertyName = $property->name;
$assignmentStatement = "\$values['" . $propertyName . "'] = \$object->" . $propertyName . ';';
$requiresGuard = $property->hasType && !($property->hasDefault || $property->allowsNull);

if (!$requiresGuard) {
return [' ' . $assignmentStatement];
}

return [
' if (isset($object->' . $propertyName . ')) {',
' ' . $assignmentStatement,
' }'
];
}

private function replaceConstructor(ClassMethod $method): void
{
$method->params = [];
Expand All @@ -145,19 +167,7 @@ private function replaceConstructor(ClassMethod $method): void
// Extract closures
$bodyParts[] = '$this->extractCallbacks[] = \\Closure::bind(static function ($object, &$values) {';
foreach ($properties as $property) {
$propertyName = $property->name;
$requiresGuard = $property->hasType && ! ($property->hasDefault || $property->allowsNull);
$indent = $requiresGuard ? ' ' : ' ';

if ($requiresGuard) {
$bodyParts[] = ' if (isset($object->' . $propertyName . ')) {';
}

$bodyParts[] = $indent . "\$values['" . $propertyName . "'] = \$object->" . $propertyName . ';';

if ($requiresGuard) {
$bodyParts[] = ' }';
}
$bodyParts = array_merge($bodyParts, $this->generatePropertyExtractCall($property));
}

$bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
Expand Down

0 comments on commit c202991

Please sign in to comment.