EnumTrait: throw InvalidArgumentException from fromString()

this is more in line with expected behaviour, since this might be used to process arbitrary user input. Only calling an undefined magic static method should throw an Error.
This commit is contained in:
Dylan K. Taylor 2019-03-31 16:07:42 +01:00
parent cdeb3ea5a6
commit 8c19f6cac8

View File

@ -76,12 +76,13 @@ trait EnumTrait{
* @param string $name
*
* @return self
* @throws \InvalidArgumentException
*/
public static function fromString(string $name) : self{
self::checkInit();
$name = strtoupper($name);
if(!isset(self::$members[$name])){
throw new \Error("Undefined enum member: " . self::class . "::" . $name);
throw new \InvalidArgumentException("Undefined enum member: " . self::class . "::" . $name);
}
return self::$members[$name];
}
@ -96,7 +97,11 @@ trait EnumTrait{
if(!empty($arguments)){
throw new \ArgumentCountError("Expected exactly 0 arguments, " . count($arguments) . " passed");
}
return self::fromString($name);
try{
return self::fromString($name);
}catch(\InvalidArgumentException $e){
throw new \Error($e->getMessage(), 0, $e);
}
}
/**