Last active
August 29, 2015 14:13
-
-
Save thekid/27e1a3f36a9e35dda20d to your computer and use it in GitHub Desktop.
When / Then / Match expression DSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| use util\cmd\Console; | |
| class One extends \lang\Object { | |
| } | |
| class Two extends \lang\Object { | |
| } | |
| class Three extends \lang\Object { | |
| } | |
| interface Result { | |
| public function get(); | |
| public function present(); | |
| public function when($expr); | |
| public function then($value); | |
| } | |
| class Next extends \lang\Object implements Result { | |
| public function __construct($match, $expr) { | |
| $this->match= $match; | |
| $this->expr= $expr; | |
| } | |
| public function get() { throw new \lang\IllegalStateException('Nothing matched'); } | |
| public function present() { return false; } | |
| public function when($expr) { | |
| $this->expr= $expr; | |
| return $this; | |
| } | |
| public function then($value) { | |
| if ($this->expr) { | |
| return new Matched($value); | |
| } else { | |
| return $this; | |
| } | |
| } | |
| public function toString() { return '(nothing matched)'; } | |
| } | |
| class Matched extends \lang\Object implements Result { | |
| public function __construct($value) { $this->value= $value; } | |
| public function get() { return $this->value; } | |
| public function present() { return true; } | |
| public function when($expr) { return $this; } | |
| public function then($value) { return $this; } | |
| public function toString() { return \xp::stringOf($this->value); } | |
| } | |
| class Match extends \lang\Object { | |
| public static function of() { | |
| return new self(); | |
| } | |
| public function when($expr) { | |
| return new Next($this, $expr); | |
| } | |
| } | |
| class Test extends \lang\Object { | |
| public static function main($args) { | |
| $element= new One(); | |
| $result= Match::of() | |
| ->when($element instanceof One)->then('One') | |
| ->when($element instanceof Two)->then('Two') | |
| ; | |
| Console::writeLine('Instance of ', $element->getClassName(), ' => ', $result); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by http://tutorials.jenkov.com/scala/match.html