Skip to content

Instantly share code, notes, and snippets.

@cobodo
Created October 31, 2013 08:02
Show Gist options
  • Save cobodo/7245826 to your computer and use it in GitHub Desktop.
Save cobodo/7245826 to your computer and use it in GitHub Desktop.
車輪を再発明
<?php
class Optional {
private $obj;
public function __construct ($obj) { $this->obj = $obj; }
private function _ocheck () {
return is_object($this->obj);
}
private function _fcheck ($func) {
return $this->_ocheck() && method_exists($this->obj, $func);
}
private function _pcheck ($prop) {
return $this->_ocheck() && property_exists($this->obj, $prop);
}
public function __call ($func, $arguments) {
if (!$this->_fcheck($func)) { return new Optional(null); }
return new Optional(call_user_func_array(array($this->obj, $func), $arguments));
}
public function __invoke () {
if (!$this->_fcheck('__invoke')) { return new Optional(null); }
return new Optional(call_user_func_array($this->obj, (array)func_get_args()));
}
public function __set ($name, $value) {
if (!$this->_pcheck($name)) { return new Optional(null); }
$this->obj->$name = $value;
return $this;
}
public function __get ($name) {
if (!$this->_pcheck($name)) { return new Optional(null); }
return new Optional($this->obj->$name);
}
public function __isset ($name) {
if (!$this->_pcheck($name)) { return false; }
return isset($this->obj->$name);
}
public function __unset ($name) {
if (!$this->_pcheck($name)) { return; }
unset($this->obj->$name);
}
public function get () {
return $this->obj;
}
/**
* map :: Optional o => o a -> (a -> b) -> o b
* @param callable $callable :: a -> b
*/
public function map ($callable = null) {
if (!is_callable($callable)) { return new Optional(null); }
return new Optional($callable($this->obj));
}
/**
* flatMap :: Optional o => o a -> (a -> o b) -> o b
* @param callable $callable :: Optional o => a -> o b
*/
public function flatMap ($callable = null) {
if (!is_callable($callable)) { return new Optional(null); }
$result = $callable($this->obj);
if (!is_object($result) || !is_a($result, 'Optional')) { return new Optional($result); }
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment