From 24f1a63c2d39825dbd5a7d2c7e5b7a9f927841b4 Mon Sep 17 00:00:00 2001 From: ignace nyamagana butera Date: Fri, 19 Jan 2024 17:54:08 +0100 Subject: [PATCH] Adding a Javascript Converter for Enum --- src/Enum/JavascriptConverter.php | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/Enum/JavascriptConverter.php b/src/Enum/JavascriptConverter.php index 1d7e253..ff208ff 100644 --- a/src/Enum/JavascriptConverter.php +++ b/src/Enum/JavascriptConverter.php @@ -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)"; } @@ -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); } @@ -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) {