Skip to content

Commit

Permalink
Round floats in UnsignedInt cast
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia committed May 7, 2024
1 parent ac3f66f commit 5e6a166
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 6 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.0

### Added

- Round floats in `UnsignedInt` cast

## v5.1.0

### Added
Expand Down
5 changes: 3 additions & 2 deletions php.dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@ WORKDIR /workdir
COPY --from=composer /usr/bin/composer /usr/bin/composer

RUN apt-get update && \
apt-get install -y \
apt-get install --yes \
git \
libzip-dev \
zip \
libicu-dev \
&& rm -rf /var/lib/apt/lists/* \
&& docker-php-ext-install \
calendar \
zip \
mysqli \
pdo_mysql \
intl \
&& rm -rf /var/lib/apt/lists/* \
&& pecl install \
xdebug \
redis \
Expand Down
19 changes: 15 additions & 4 deletions src/Casts/UnsignedInt.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ class UnsignedInt implements CastsAttributes
*/
public function get($model, $key, $value, $attributes): int
{
assert(is_int($value));

return max(0, $value);
return $this->cast($value);
}

/**
Expand All @@ -33,7 +31,20 @@ public function get($model, $key, $value, $attributes): int
*/
public function set($model, $key, $value, $attributes): int
{
assert(is_int($value));
return $this->cast($value);
}

protected function cast(mixed $value): int
{
if (is_float($value)) {
$value = (int) round($value);
}

if (! is_int($value)) {
$type = gettype($value);
$valueString = var_export($value, true);
throw new \RuntimeException("Expected int, got {$type}: {$valueString}.");
}

return max(0, $value);
}
Expand Down
12 changes: 12 additions & 0 deletions tests/Casts/UnsignedIntTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,19 @@ public function testCast(): void
$model->unsigned_int = 2;
self::assertSame(2, $model->getRawAttribute('unsigned_int'));

$model->unsigned_int = 2.4999; // @phpstan-ignore-line should round floats
self::assertSame(2, $model->getRawAttribute('unsigned_int'));

$model->unsigned_int = 2.5001; // @phpstan-ignore-line should round floats
self::assertSame(3, $model->getRawAttribute('unsigned_int'));

$model->setRawAttribute('unsigned_int', -1);
self::assertSame(0, $model->unsigned_int);

$model->setRawAttribute('unsigned_int', 1.1);
self::assertSame(1, $model->unsigned_int);

$this->expectExceptionObject(new \RuntimeException('Expected int, got string: "foo".'));
$model->unsigned_int = 'foo'; // @phpstan-ignore-line intentionally wrong
}
}

0 comments on commit 5e6a166

Please sign in to comment.