From 9033d95292cafd45f6b5c807f1e5a564cd4c73ac Mon Sep 17 00:00:00 2001 From: Alberto Date: Fri, 13 Dec 2024 11:32:22 -0500 Subject: [PATCH] PHP discriminated unions proposal --- seed/php-sdk/unions/src/Union/Types/Shape.php | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 seed/php-sdk/unions/src/Union/Types/Shape.php diff --git a/seed/php-sdk/unions/src/Union/Types/Shape.php b/seed/php-sdk/unions/src/Union/Types/Shape.php new file mode 100644 index 00000000000..51d28e82051 --- /dev/null +++ b/seed/php-sdk/unions/src/Union/Types/Shape.php @@ -0,0 +1,104 @@ +type = $this->options['type'] ?? ShapeType::UNKNOWN; + $this->circle = $this->options['circle'] ?? null; + $this->square = $this->options['square'] ?? null; + $this->unknown = $this->options['unknown'] ?? null; + } + + /** + * @param + */ + static function circle(Circle $circle): Shape + { + return new Shape([ + 'type' => ShapeType::CIRCLE, + 'circle' => $circle + ]); + } + + static function square(Square $square): Shape + { + return new Shape([ + 'type' => ShapeType::SQUARE, + 'square' => $square + ]); + } + + static function _unknown(object $unknown): Shape + { + return new Shape([ + 'unknown' => $unknown + ]); + } + + public function isCircle(): bool + { + return $this->type == ShapeType::CIRCLE; + } + + public function isSquare(): bool + { + return $this->type == ShapeType::SQUARE; + } + + public function visit(ShapeVisitor $visitor) + { + return match ($this->type) { + ShapeType::CIRCLE => $visitor->visitCircle($this->circle), + ShapeType::SQUARE => $visitor->visitSquare($this->square), + ShapeType::UNKNOWN => $visitor->_visitUnknown($this), + }; + } +}