From 206940bf59c85de1ff1e9841e0cb3f103f5f072f Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Fri, 16 Oct 2026 14:45:26 +0200 Subject: [PATCH] EnumCast: Use `::tryFrom` in fromDb() Schema changes may remove or add new values to an enum, so existing rows should not throw an exception. The consumer is supposed to ensure only valid values are persisted, hence toDb() still throws. Existing rows have to be seen as always valid, though. --- src/Behavior/EnumCast.php | 14 ++------------ tests/Behavior/EnumCastTest.php | 4 +--- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/src/Behavior/EnumCast.php b/src/Behavior/EnumCast.php index 36a50ab6..752deb14 100644 --- a/src/Behavior/EnumCast.php +++ b/src/Behavior/EnumCast.php @@ -12,7 +12,7 @@ * Convert backed-enum database values to and from PHP enum instances * * The enum's backing value (string|int) is stored in the database. On retrieval the raw scalar - * is converted to the corresponding enum case via {@see BackedEnum::from()}; on persistence the + * is converted to the corresponding enum case via {@see BackedEnum::tryFrom()}; on persistence the * enum instance is unwrapped back to its backing value. Null is preserved as null in both directions. * * ```php @@ -47,8 +47,6 @@ public function __construct(string $enum, array $properties) * @param int|string|null $value * * @return ?BackedEnum - * - * @throws ValueConversionException */ public function fromDb($value, $key, $_) { @@ -56,15 +54,7 @@ public function fromDb($value, $key, $_) return $value; } - try { - return $this->enum::from($value); - } catch (ValueError $e) { - throw new ValueConversionException(sprintf( - "%s (key: '%s')", - $e->getMessage(), - $key - )); - } + return $this->enum::tryFrom($value); } /** diff --git a/tests/Behavior/EnumCastTest.php b/tests/Behavior/EnumCastTest.php index cb6f24b7..0384dd3f 100644 --- a/tests/Behavior/EnumCastTest.php +++ b/tests/Behavior/EnumCastTest.php @@ -79,9 +79,7 @@ public function testToDbPassesThroughNull(): void public function testFromDbThrowsForUnknownBackingValue(): void { - $this->expectException(ValueConversionException::class); - - $this->behavior->fromDb('purple', 'color', null); + $this->assertNull($this->behavior->fromDb('purple', 'color', null)); } public function testFromDbIsIdempotentWhenValueIsAlreadyAnEnumInstance(): void