|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace Bug11430Methods; |
| 4 | + |
| 5 | +use function PHPStan\Testing\assertType; |
| 6 | + |
| 7 | +/** |
| 8 | + * @template T |
| 9 | + * |
| 10 | + * @implements \IteratorAggregate<T> |
| 11 | + */ |
| 12 | +abstract class Option implements \IteratorAggregate |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @template S |
| 16 | + * @template U |
| 17 | + * |
| 18 | + * @param S $value The actual return value. |
| 19 | + * @param U $noneValue The value which should be considered "None"; null by |
| 20 | + * default. |
| 21 | + * |
| 22 | + * @return (S is U ? None : Option<S>) |
| 23 | + */ |
| 24 | + public static function fromValue($value, $noneValue = null) |
| 25 | + { |
| 26 | + if ($value === $noneValue) { |
| 27 | + return None::create(); |
| 28 | + } |
| 29 | + |
| 30 | + return new Some($value); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * @extends Option<mixed> |
| 36 | + */ |
| 37 | +final class None extends Option |
| 38 | +{ |
| 39 | + /** @var None|null */ |
| 40 | + private static $instance; |
| 41 | + |
| 42 | + /** |
| 43 | + * @return None |
| 44 | + */ |
| 45 | + public static function create(): self |
| 46 | + { |
| 47 | + if (null === self::$instance) { |
| 48 | + self::$instance = new self(); |
| 49 | + } |
| 50 | + |
| 51 | + return self::$instance; |
| 52 | + } |
| 53 | + |
| 54 | + public function getIterator(): \EmptyIterator |
| 55 | + { |
| 56 | + return new \EmptyIterator(); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * @template T |
| 62 | + * |
| 63 | + * @extends Option<T> |
| 64 | + */ |
| 65 | +final class Some extends Option |
| 66 | +{ |
| 67 | + /** @var T */ |
| 68 | + private $value; |
| 69 | + |
| 70 | + /** |
| 71 | + * @param T $value |
| 72 | + */ |
| 73 | + public function __construct($value) |
| 74 | + { |
| 75 | + $this->value = $value; |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * @return \ArrayIterator<int, T> |
| 80 | + */ |
| 81 | + public function getIterator(): \ArrayIterator |
| 82 | + { |
| 83 | + return new \ArrayIterator([$this->value]); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | + |
| 88 | +class Test |
| 89 | +{ |
| 90 | + /** @var Option<string> */ |
| 91 | + public Option $name; |
| 92 | +} |
| 93 | + |
| 94 | +$test = new Test(); |
| 95 | +/** @var ?string $foo */ |
| 96 | +$foo = null; |
| 97 | +$test->name = Option::fromValue($foo); |
| 98 | +assertType('Bug11430Methods\Option<string>', $test->name); |
0 commit comments