Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save thekid/27e1a3f36a9e35dda20d to your computer and use it in GitHub Desktop.

Select an option

Save thekid/27e1a3f36a9e35dda20d to your computer and use it in GitHub Desktop.
When / Then / Match expression DSL
<?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);
}
}
@thekid
Copy link
Author

thekid commented Jan 16, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment