Skip to content

Commit

Permalink
Add ability to parse enum value from constant name
Browse files Browse the repository at this point in the history
  • Loading branch information
populov committed Nov 6, 2020
1 parent 00f81b3 commit 1db018f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changes History

1.2.0
-----
Add ability to parse enum value from constant name

1.1.1
-----
Add **__isset** method to DTO to have proper properties check on object
Expand Down
15 changes: 15 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,21 @@ public static function validate($value, $strict = true)
return $value;
}

/**
* Get value by constant name, case insensitive
*
* @param string $name Constant name
* @return mixed
*/
public static function parse($name) {
$nameStr = strtoupper($name);
$constants = static::getConstants();
if (!array_key_exists($nameStr, $constants)) {
throw new InvalidEnumValueException(array_keys(static::getConstants()));
}
return $constants[$nameStr];
}

/**
* Converts value to a string
*
Expand Down
27 changes: 27 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Saritasa\Tests;

use App\Enums\ParseableEnum;
use PHPUnit\Framework\TestCase;
use Saritasa\Enum;
use Saritasa\Exceptions\InvalidEnumValueException;
Expand Down Expand Up @@ -54,6 +55,32 @@ public function testValidate()
static::expectException(InvalidEnumValueException::class);
TestEnum::validate('bullshit');
}

public function testParse()
{
$testEnum = new class (1) extends Enum {
const ONE = 1;
const TWO = 2;
};

self::assertEquals(1, $testEnum->parse('One'));
self::assertEquals(1, $testEnum->parse('ONE'));
self::assertEquals(1, $testEnum->parse('one'));
self::assertEquals(2, $testEnum->parse('Two'));
self::assertEquals(2, $testEnum->parse('TWO'));
self::assertEquals(2, $testEnum->parse('two'));
}

public function testInvalidValueException()
{
$testEnum = new class (1) extends Enum {
const ONE = 1;
const TWO = 2;
};

$this->expectException(InvalidEnumValueException::class);
$testEnum->parse('Three');
}
}

class TestEnum extends Enum {
Expand Down

0 comments on commit 1db018f

Please sign in to comment.