Skip to content

Instantly share code, notes, and snippets.

@skollro
Last active April 1, 2018 14:53
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skollro/384b0470d4d8c348d63986608fb9eb80 to your computer and use it in GitHub Desktop.
Save skollro/384b0470d4d8c348d63986608fb9eb80 to your computer and use it in GitHub Desktop.
<?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);
}
@arandilopez
Copy link

Looks great, I would change case function to when in name

match($something)->when('is_array', "This is a array!");

@skollro
Copy link
Author

skollro commented Mar 28, 2018

Thanks for your feedback! when is the word I was looking for. I've updated the code :)

@skollro
Copy link
Author

skollro commented Mar 30, 2018

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