Commit 0696ddde authored by Jan Kuchař's avatar Jan Kuchař

Enum::fromScalar(): checks if value exists and throws checked/runtime...

Enum::fromScalar(): checks if value exists and throws checked/runtime exception when that case happens
parent 07771692
Pipeline #14305 passed with stages
in 1 minute and 21 seconds
......@@ -25,7 +25,10 @@
"autoload": {
"psr-4": {
"Grifart\\Enum\\": "src"
}
},
"classmap": [
"src/exceptions.php"
]
},
"require-dev": {
......@@ -33,7 +36,9 @@
"phpstan/phpstan": "^0.8.5"
},
"autoload-dev": {
"files": [
"src/exceptions.php"
]
}
}
......@@ -36,7 +36,9 @@ abstract class Enum
/**
* Builds enumeration from its scalar value.
* @param string|int $scalar
* @return static
* @throws MissingValueValueException if there is no value for given scalar
*/
public static function fromScalar($scalar): Enum
{
......
......@@ -3,6 +3,7 @@
namespace Grifart\Enum\Internal;
use Grifart\Enum\Enum;
use Grifart\Enum\MissingValueValueException;
final class Meta
{
......@@ -76,8 +77,15 @@ final class Meta
return $result;
}
/**
* @param int|string $scalar
* @throws MissingValueValueException if there is no value for given scalar
*/
public function getValueForScalar($scalar): Enum
{
if (!isset($this->scalarToValue[$scalar])) {
throw new MissingValueValueException("There is no value for enum '{$this->class}' and scalar value '$scalar'.");
}
return $this->scalarToValue[$scalar];
}
}
<?php declare(strict_types=1);
/**
* Contains all exceptions used in project.
*
* - Usage exceptions: leads directly to fix by programmer. They are never caught and should never happen on production.
* - Runtime exception: they represent valid case in domain logic. They should be handled at runtime and caught.
* Therefore every error should have separate exception type.
*/
namespace Grifart\Enum;
// Project root exceptions:
final class UsageException extends \LogicException {}
abstract class RuntimeException extends \RuntimeException {}
final class MissingValueValueException extends RuntimeException {}
\ No newline at end of file
<?php declare(strict_types=1);
use Grifart\Enum\MissingValueValueException;
require __DIR__ . '/../bootstrap.php';
/**
......@@ -10,4 +13,10 @@ class Enum1 extends \Grifart\Enum\Enum
protected const VALUE = 'value';
}
Enum1::fromScalar('non-existing');
\Tester\Assert::exception(
function () {
Enum1::fromScalar('non-existing');
},
MissingValueValueException::class,
"There is no value for enum 'Enum1' and scalar value 'non-existing'."
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment