|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace TH\Maybe\Tests\Unit\Option; |
| 4 | + |
| 5 | +use PHPUnit\Framework\Assert; |
| 6 | +use PHPUnit\Framework\TestCase; |
| 7 | +use TH\Maybe\Option; |
| 8 | +use TH\Maybe\Tests\Provider; |
| 9 | + |
| 10 | +final class IfyTest extends TestCase |
| 11 | +{ |
| 12 | + use Provider\Options; |
| 13 | + |
| 14 | + /** |
| 15 | + * @dataProvider fromValueMatrix |
| 16 | + * @param Option<mixed> $expected |
| 17 | + */ |
| 18 | + public function testIfy(Option $expected, mixed $value, mixed $noneValue, bool $strict = true): void |
| 19 | + { |
| 20 | + Assert::assertEquals($expected, Option\ify(static fn () => $value, $noneValue, strict: $strict)()); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * @dataProvider fromValueMatrix |
| 25 | + * @param Option<mixed> $expected |
| 26 | + */ |
| 27 | + public function testTryOf(Option $expected, mixed $value, mixed $noneValue, bool $strict = true): void |
| 28 | + { |
| 29 | + Assert::assertEquals($expected, Option\tryIfy(static fn () => $value, $noneValue, strict: $strict)()); |
| 30 | + } |
| 31 | + |
| 32 | + public function testOfDefaultToNull(): void |
| 33 | + { |
| 34 | + Assert::assertEquals(Option\none(), Option\ify(static fn () => null)()); |
| 35 | + Assert::assertEquals(Option\some(1), Option\ify(static fn () => 1)()); |
| 36 | + } |
| 37 | + |
| 38 | + public function testTryOfDefaultToNull(): void |
| 39 | + { |
| 40 | + Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => null)()); |
| 41 | + Assert::assertEquals(Option\some(1), Option\tryIfy(static fn () => 1)()); |
| 42 | + } |
| 43 | + |
| 44 | + public function testOfDefaultToStrict(): void |
| 45 | + { |
| 46 | + $o = (object)[]; |
| 47 | + |
| 48 | + Assert::assertEquals(Option\none(), Option\ify(static fn () => $o, (object)[], strict: false)()); |
| 49 | + Assert::assertEquals($o, Option\ify(static fn () => $o, (object)[])()->unwrap()); |
| 50 | + } |
| 51 | + |
| 52 | + public function testTryOfDefaultToStrict(): void |
| 53 | + { |
| 54 | + $o = (object)[]; |
| 55 | + |
| 56 | + Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => $o, (object)[], strict: false)()); |
| 57 | + Assert::assertEquals($o, Option\tryIfy(static fn () => $o, (object)[])()->unwrap()); |
| 58 | + } |
| 59 | + |
| 60 | + public function testTryOfExeptions(): void |
| 61 | + { |
| 62 | + // @phpstan-ignore-next-line |
| 63 | + Assert::assertEquals(Option\none(), Option\tryIfy(static fn () => new \DateTimeImmutable("nope"))()); |
| 64 | + |
| 65 | + try { |
| 66 | + // @phpstan-ignore-next-line |
| 67 | + Option\tryIfy(static fn () => 1 / 0)(); |
| 68 | + Assert::fail("An exception should have been thrown"); |
| 69 | + } catch (\DivisionByZeroError) { |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments