|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use PhpTypedValues\Exception\FloatTypeException; |
| 6 | +use PhpTypedValues\Float\FloatNonNegative; |
| 7 | +use PhpTypedValues\Undefined\Alias\Undefined; |
| 8 | + |
| 9 | +it('FloatNonNegative::tryFromString returns value for >= 0.0 and Undefined otherwise', function (): void { |
| 10 | + $ok0 = FloatNonNegative::tryFromString('0'); |
| 11 | + $ok = FloatNonNegative::tryFromString('0.5'); |
| 12 | + $bad = FloatNonNegative::tryFromString('-0.1'); |
| 13 | + $badStr = FloatNonNegative::tryFromString('abc'); |
| 14 | + |
| 15 | + expect($ok0) |
| 16 | + ->toBeInstanceOf(FloatNonNegative::class) |
| 17 | + ->and($ok0->value())->toBe(0.0) |
| 18 | + ->and($ok) |
| 19 | + ->toBeInstanceOf(FloatNonNegative::class) |
| 20 | + ->and($ok->value())->toBe(0.5) |
| 21 | + ->and($bad)->toBeInstanceOf(Undefined::class) |
| 22 | + ->and($badStr)->toBeInstanceOf(Undefined::class); |
| 23 | +}); |
| 24 | + |
| 25 | +it('FloatNonNegative::tryFromFloat returns value for >= 0 and Undefined otherwise', function (): void { |
| 26 | + $ok = FloatNonNegative::tryFromFloat(0); |
| 27 | + $bad = FloatNonNegative::tryFromFloat(-1); |
| 28 | + |
| 29 | + expect($ok) |
| 30 | + ->toBeInstanceOf(FloatNonNegative::class) |
| 31 | + ->and($ok->value()) |
| 32 | + ->toBe(0.0) |
| 33 | + ->and($bad) |
| 34 | + ->toBeInstanceOf(Undefined::class); |
| 35 | +}); |
| 36 | + |
| 37 | +it('FloatNonNegative throws on negative values in ctor and fromFloat', function (): void { |
| 38 | + expect(fn() => new FloatNonNegative(-0.1)) |
| 39 | + ->toThrow(FloatTypeException::class, 'Expected non-negative float, got "-0.1"') |
| 40 | + ->and(fn() => FloatNonNegative::fromFloat(-1.0)) |
| 41 | + ->toThrow(FloatTypeException::class, 'Expected non-negative float, got "-1"'); |
| 42 | +}); |
| 43 | + |
| 44 | +it('FloatNonNegative::fromString enforces numeric and non-negativity', function (): void { |
| 45 | + // Non-numeric |
| 46 | + expect(fn() => FloatNonNegative::fromString('abc')) |
| 47 | + ->toThrow(FloatTypeException::class, 'String "abc" has no valid float value'); |
| 48 | + |
| 49 | + // Non-negativity |
| 50 | + expect(fn() => FloatNonNegative::fromString('-0.5')) |
| 51 | + ->toThrow(FloatTypeException::class, 'Expected non-negative float, got "-0.5"'); |
| 52 | + |
| 53 | + // Success path |
| 54 | + $v = FloatNonNegative::fromString('0.75'); |
| 55 | + expect($v->value())->toBe(0.75); |
| 56 | +}); |
0 commit comments