Skip to content

Commit

Permalink
Adding a Javascript Converter for Enum
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Jan 19, 2024
1 parent fa5d063 commit 24f1a63
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/Enum/JavascriptConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,11 @@ public function convertToObject(string $enumClass, ?string $objectName = null):
$eol = $this->indentSize > 0 ? "\n" : '';
$output = array_reduce(
$enumClass::cases(),
fn (string $output, BackedEnum $enum): string => $output.$space.$this->formatPropertyName($enum).": ".$this->formatPropertyValue($enum)."},$eol",
fn (string $output, BackedEnum $enum): string => $output.$space.$this->formatPropertyName($enum).': '.$this->formatPropertyValue($enum).','.$eol,
''
);

$output = "{".$eol.$output."}";
$output = '{'.$eol.$output.'}';
if ($this->useImmutability) {
$output = "Object.freeze($output)";
}
Expand All @@ -200,17 +200,16 @@ public function convertToClass(string $enumClass, string $className = ''): strin
{
$this->filterBackedEnum($enumClass);

$eol = $this->indentSize > 0 ? "\n" : '';
$className = $this->sanitizeName($className, $enumClass);
$space = str_repeat(' ', $this->indentSize);
$eol = $this->indentSize > 0 ? "\n" : '';
$classBody = array_reduce(
$enumClass::cases(),
fn (string $output, BackedEnum $enum): string => $output
.$space."static {$this->formatPropertyName($enum)} = new $className({$this->formatPropertyValue($enum)})\n",
fn (string $output, BackedEnum $enum): string => $output.$space."static {$this->formatPropertyName($enum)} = new $className({$this->formatPropertyValue($enum)})$eol",
''
);

$output = "class $className {\n$classBody\n$space"."constructor(name) {\n$space$space"."this.name = name\n$space}\n}\n";
$output = 'class '.$className.' {'.$eol.$classBody.$eol.$space.'constructor(name) {'.$eol.$space.$space.'this.name = name'.$eol.$space.'}'.$eol.'}'.$eol;

return $this->formatOutput($output);
}
Expand Down Expand Up @@ -262,11 +261,7 @@ private function sanitizeName(?string $className, string $enumClass): ?string
return (string) array_pop($parts);
}

/**
* @param string $output
*
* @return string
*/

public function formatOutput(string $output): string
{
return match ($this->useExport) {
Expand Down

0 comments on commit 24f1a63

Please sign in to comment.