Skip to content

ustream/option

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ustream Option monad Build Status

This is a PHP interpretation of the Option type with monadic structure. We beleive that the tests document the behavior and even though the implementation is similar to php-option there are some important differences we need to highlight.

There is apply instead of map and flatMap

We found it useful, that the monadic computation may decide to return with an arbitrary type, that will be converted to an Option if necessary.

The rules for Some::apply is as follows:

  • If the return type is not an Option it will be wrapped in Some
  • If there is no return value (actually the return value is null) it will be translated to None
  • If the return type is an Option it will be passed through (the same as for flatMap)

Examples

Wrapping a non Option type:

$result = someMethodReturningAnOptionalString($params)
	->apply(
		function ($result) {
			return $result . ' is a string!';
		})
	->getOrElse('default');

No need to explicitly return with None:

$module = $dataMaybe
    ->apply(
		function ($data) {
			if (isset($data['moduleConfig'])) {
				if (count($data['moduleConfig']) == 1) {
					return key($data['moduleConfig']);
				} elseif (count($data['moduleConfig']) > 1) {
					return 'full';
				}
			}
		}
	)
	->getOrElse('unknown');

There is otherwise instead of orElse with LazyOption

We use None::otherwise as the mirror of Some::apply.

Examples

Combining apply and otherwise:

header(
    locate($_SERVER["DOCUMENT_URI"])
		->apply(
			function ($location) {
				statsdIncrement('302');
				return 'Location: ' . $location;
			}
		)
		->otherwise(
			function () {
				statsdIncrement('404');
			}
		)
		->getOrElse("HTTP/1.0 404 Not Found")
);

Creating a chain of fallback functions:

return Ustream\Option\None::create()
    ->otherwise($this->ustreamPicture($userId, $size))
	->otherwise($this->facebookPictureFromSession($facebookNetwork, $isSecureAccess))
	->getOrElse($this->naPicture($size));

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages