Esempio n. 1
0
 /**
  * Creates a new ManyMaybe instance from the given collection,
  * thereby composing each collection item into an Maybe monad.
  *
  * @param array $values
  */
 protected function __construct(array $values)
 {
     $unit = function ($value) {
         return Maybe::unit($value);
     };
     parent::__construct(array_map($unit, $values));
 }
    {
        if ($value instanceof Maybe) {
            return $value;
        }
        return new static($value);
    }
    // Places an object into the monad if the isNothing function returns true
    public function bind(callable $function)
    {
        return $this->isNothing() ? $this : static::unit($function($this->container));
    }
    public function isNothing()
    {
        return $this->container === false;
    }
}
// Object to test
$vehicle = new Vehicle(1, 'golf', 'red', 12000, true, 1000);
// Ruleset for type, color and mileage
$type = function ($value) {
    return Maybe::unit($value->type == 'golf' ? $value : false);
};
$color = function ($value) {
    return Maybe::unit($value->color == 'red' ? $value : false);
};
$mileage = function ($value) {
    return Maybe::unit($value->mileage == 12000 ? $value : false);
};
// Execution. On success an object will be returned
$test = Maybe::unit($vehicle)->bind($type)->bind($color)->bind($mileage);
var_dump($test->get());