Last active
April 1, 2018 14:53
-
-
Save skollro/384b0470d4d8c348d63986608fb9eb80 to your computer and use it in GitHub Desktop.
This file contains 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 | |
class Match | |
{ | |
protected $value; | |
protected $result; | |
protected $hasMatch; | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
$this->result = null; | |
$this->hasMatch = false; | |
} | |
public function when($condition, $result) | |
{ | |
if ($this->hasMatch) { | |
return $this; | |
} | |
if (is_callable($condition) ? $condition($this->value) : $condition) { | |
$this->result = $result; | |
$this->hasMatch = true; | |
} | |
return $this; | |
} | |
public function otherwise($value) | |
{ | |
if ($this->hasMatch) { | |
return is_callable($this->result) ? ($this->result)($this->value) : $this->result; | |
} | |
return is_callable($value) ? $value($this->value) : $value; | |
} | |
public function otherwiseThrow($value) | |
{ | |
throw (new self($value)) | |
->when(is_callable($value), function ($value) { | |
return $value($this->value); | |
}) | |
->when($value instanceof \Throwable, $value) | |
->otherwise(function ($value) { | |
return new $value; | |
}); | |
} | |
} | |
function match($value) | |
{ | |
return new Match($value); | |
} |
Thanks for your feedback! when
is the word I was looking for. I've updated the code :)
I've created a package for this: https://github.com/skollro/otherwise
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks great, I would change
case
function towhen
in name