diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f3ce76..e172c4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ See [GitHub releases](https://github.com/mll-lab/laravel-utils/releases). ## Unreleased +## v5.2.1 + +### Fixed + +- Handle `null` in `UnsignedInt` cast + ## v5.2.0 ### Added diff --git a/src/Casts/UnsignedInt.php b/src/Casts/UnsignedInt.php index 4339352..c2cc410 100644 --- a/src/Casts/UnsignedInt.php +++ b/src/Casts/UnsignedInt.php @@ -19,7 +19,7 @@ class UnsignedInt implements CastsAttributes * @param string $key * @param array $attributes */ - public function get($model, $key, $value, $attributes): int + public function get($model, $key, $value, $attributes): ?int { return $this->cast($value); } @@ -29,13 +29,17 @@ public function get($model, $key, $value, $attributes): int * @param string $key * @param array $attributes */ - public function set($model, $key, $value, $attributes): int + public function set($model, $key, $value, $attributes): ?int { return $this->cast($value); } - protected function cast(mixed $value): int + protected function cast(mixed $value): ?int { + if ($value === null) { + return null; + } + if (is_float($value)) { $value = (int) round($value); } diff --git a/tests/Casts/UnsignedIntTest.php b/tests/Casts/UnsignedIntTest.php index 8317f79..00409a9 100644 --- a/tests/Casts/UnsignedIntTest.php +++ b/tests/Casts/UnsignedIntTest.php @@ -9,8 +9,13 @@ final class UnsignedIntTest extends TestCase public function testCast(): void { $model = new CastsModel(); + + $model->setRawAttribute('unsigned_int', null); self::assertNull($model->unsigned_int); + $model->unsigned_int = null; + self::assertNull($model->getRawAttribute('unsigned_int')); + $model->unsigned_int = -1; self::assertSame(0, $model->getRawAttribute('unsigned_int')); @@ -35,7 +40,7 @@ public function testCast(): void $model->setRawAttribute('unsigned_int', 1.1); self::assertSame(1, $model->unsigned_int); - $this->expectExceptionObject(new \RuntimeException('Expected int, got string: "foo".')); + $this->expectExceptionObject(new \RuntimeException("Expected int, got string: 'foo'.")); $model->unsigned_int = 'foo'; // @phpstan-ignore-line intentionally wrong } }