Skip to content

Commit

Permalink
Merge pull request #5 from chaker2710/master
Browse files Browse the repository at this point in the history
Add native enum support (PHP 8.1)
  • Loading branch information
modstore authored Aug 17, 2022
2 parents 1234cd5 + 5e13abb commit b422579
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Console/Commands/GenerateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,17 @@ protected function writeFile(string $class)

$reflection = new \ReflectionClass($class);

$is_enum = method_exists($reflection, 'isEnum') && $reflection->isEnum();

$outputString = '';
foreach ($reflection->getConstants() as $key => $value) {
if (gettype($value) == gettype(" ") ) {
$outputString .= sprintf("export const %s = \"%s\"\n", $key, $value);
if ($is_enum) {
$value = property_exists($value, 'value') ? $value->value : $value->name;
}
else {

if (gettype($value) == gettype(" ")) {
$outputString .= sprintf("export const %s = \"%s\"\n", $key, $value);
} else {
$outputString .= sprintf("export const %s = %s\n", $key, $value);
}
}
Expand Down
6 changes: 6 additions & 0 deletions tests/Console/Commands/GenerateCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,18 @@ public function testGenerate()
// Include a couple of classes for this test.
include('tests/resources/Enums/Status.php');
include('tests/resources/Enums/Sub/Type.php');
include('tests/resources/Enums/Native/BackedString.php');
include('tests/resources/Enums/Native/Base.php');
include('tests/resources/Enums/Native/BackedInt.php');

Artisan::call('enum-js:generate');

$generatedFiles = Storage::disk(config('laravel-enum-js.output_disk'))->allFiles();

$this->assertSame([
'Native/BackedInt.js',
'Native/BackedString.js',
'Native/Base.js',
'Status.js',
'Sub/Type.js',
], $generatedFiles);
Expand Down
9 changes: 9 additions & 0 deletions tests/resources/Enums/Native/BackedInt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Enums\Native;

enum BackedInt : int
{
case Value1 = 1;
case Value2 = 2;
}
9 changes: 9 additions & 0 deletions tests/resources/Enums/Native/BackedString.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Enums\Native;

enum BackedString : string
{
case Value1 = 'value-1';
case Value2 = 'value-2';
}
9 changes: 9 additions & 0 deletions tests/resources/Enums/Native/Base.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Enums\Native;

enum Base
{
case Value1;
case Value2;
}

0 comments on commit b422579

Please sign in to comment.