Skip to content

Commit

Permalink
Handle null in UnsignedInt cast
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed May 7, 2024
1 parent 5e6a166 commit 8c51ded
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions src/Casts/UnsignedInt.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class UnsignedInt implements CastsAttributes
* @param string $key
* @param array<array-key, mixed> $attributes
*/
public function get($model, $key, $value, $attributes): int
public function get($model, $key, $value, $attributes): ?int
{
return $this->cast($value);
}
Expand All @@ -29,13 +29,17 @@ public function get($model, $key, $value, $attributes): int
* @param string $key
* @param array<array-key, mixed> $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);
}
Expand Down
7 changes: 6 additions & 1 deletion tests/Casts/UnsignedIntTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));

Expand All @@ -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
}
}

0 comments on commit 8c51ded

Please sign in to comment.