Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mkjpryor committed Feb 2, 2015
0 parents commit 9069086
Show file tree
Hide file tree
Showing 6 changed files with 508 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Zed editor
.zedstate

# Composer
composer.lock
composer.phar
vendor/

# Test files
index.php
main.php
21 changes: 21 additions & 0 deletions LICENCE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Matt Pryor

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
155 changes: 155 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
# mkjpryor/option #

Simple option and result classes for PHP, inspired by Scala's Option, Haskell's Maybe and Rust's Result.

The Option type provides additional functionality over nullable types for operating on values that may or may not be present.

The Result type also includes a reason for the failure (an exception), and allows errors to be propagated without worrying about specifically handling them.


## Installation ##

`mkjpryor/option` can be installed via [Composer](https://getcomposer.org/):

```bash
php composer.phar require mkjpryor/option dev-master
```


## Usage ##

### Creating an Option ###

```
<?php
use Mkjp\Option\Option;
// Creates a non-empty option containing the value 10
$o1 = Option::just(10);
// Creates an empty option
$o2 = Option::none();
// Creates an option from a nullable value
// If null is given, an empty option is created
$o3 = Option::from(10);
$o3 = Option::from(null);
```

### Creating a Result ###

```
<?php
use Mkjp\Option\Result;
// Create a successful result with the given value
$r1 = Result::success(42);
// Create an errored result with the given error
$r2 = Result::error(new \Exception("Some error occurred"));
// Create a result by trying some operation that might fail
// Creates a success if the function returns successfully
// Creates an error if the function throws an exception
$r3 = Result::try_(() => {
// Some operation that might fail with an exception
});
```

### Retrieving a value from an Option (or Result) ###

The underlying value can be retrieved from an `Option` in an unsafe or safe manner (N.B. the same methods are available for retrieving a value from a `Result`):

```
<?php
// UNSAFE - throws a LogicException if the option is empty
$val = $opt->get();
// Returns the Option's value if it is non-empty, 0 otherwise
$val = $opt->getOrDefault(0);
// Returns the Option's value if it is non-empty, otherwise the result of evaluating the given function
// Useful if the default value is expensive to compute
$val = $opt->getOrElse(function() { return 0; });
// Return the Option's value if it is non-empty, null otherwise
$val = $opt->getOrNull();
```

### Manipulating options and results ###

`Option`s and `Result`s have several methods for manipulating them in an 'empty-safe' manner, e.g. `map`, `filter`. See the code for more details.


## Examples ##

In the following example, we want to retrieve a user by id from the database and welcome them. If the user does not exist, we want to welcome them as a guest.

```
<?php
use Mkjp\Option\Option;
use Mkjp\Option\Result;
/**
* Simple user class
*/
class User {
public $id;
public $username;
public function __construct($id, $username) {
$this->id = $id;
$this->username = $username;
}
}
/**
* Fetches a user from a database by their id
*
* Note how we return a Result that may contain an Option
* This is because there are three possible outcomes that are semantically different:
* 1. We successfully find a user
* 2. The user doesn't exist in the database (this isn't an error - it is expected and must be handled)
* 3. There is an error querying the database
*/
function findUserById($id) {
// Assume DB::execute throws a DBError if there is an error while querying
$result = Result::try_(function() use($id) {
return DB::execute("SELECT * FROM users WHERE id = ?", $id);
});
// Use the error propagation to our advantage
return $result->map(function($data) {
if( count($data) > 0 ) {
return Option::just(new User($data[0]["id"], $data[0]["username"]));
}
else {
return Option::none();
}
});
}
$id = 1234; // This would come from request params or something similar
// Print an appropriate welcome message for the user
echo "Hello, " . findUserById($id)
// In our circumstances, a DB error is like not finding a user
->orElse(function($e) {
return Result::success(Option::none());
})
// Get the username from the optional user
->map(function($o) {
return $o->map(function($u) { return $u->username; })
->getOrDefault("Guest")
})
// We can safely use get since we know it won't be an error
->get();
```

## License ##

This code is licensed under the terms of the MIT licence.
27 changes: 27 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name" : "mkjpryor/option",
"type" : "library",
"description" : "Simple option and result types for PHP",
"homepage" : "https://github.com/mkjpryor/option",
"authors" : [
{
"name" : "Matt Pryor",
"email" : "[email protected]",
"role" : "Developer"
}
],
"license" : "MIT",

"require" : {
},

"require-dev" : {
"phpunit/phpunit" : "4.*"
},

"autoload" : {
"psr-4" : {
"Mkjp\\Option\\" : "src"
}
}
}
132 changes: 132 additions & 0 deletions src/Option.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace Mkjp\Option;


/**
* Class representing a value that can be present or not
*/
final class Option implements \IteratorAggregate {
private $value;

/**
* Private constructor to force instantiation through factory methods
*/
private function __construct($value) {
$this->value = $value;
}

/**
* Returns the result of applying $f to the value of this option if it is non-empty
*
* $f should take the wrapped value and return another option
*/
public function andThen(callable $f) {
return !$this->isEmpty() ? $f($this->get()) : Option::none();
}

/**
* Returns this option if it is non-empty and $p returns true
*
* $p should take the wrapped value and return a boolean
*/
public function filter(callable $p) {
return !$this->isEmpty() && $p($this->get()) ? $this : Option::none();
}

/**
* Returns the option's value
*
* If the option is empty, a \LogicException is thrown
*
* @throws \LogicException
*/
public function get() {
if( $this->value === null )
throw new \LogicException("Cannot get value from empty option");

return $this->value;
}

/**
* Returns an iterator for this option
*
* If this option is non-empty, the iterator will produce the single element
* If this option is empty, it will be an empty iterator
*/
public function getIterator() {
if( !$this->isEmpty() ) yield $this->get();
}

/**
* Returns the option's value if it is non-empty, $default otherwise
*/
public function getOrDefault($default) {
return $this->isEmpty() ? $default : $this->get();
}

/**
* Returns the option's value if it is non-empty, otherwise the result of evaluating
* $f
*
* $f should take no arguments and return a value
*/
public function getOrElse(callable $f) {
return $this->isEmpty() ? $f() : $this->get();
}

/**
* Returns the option's value if it is non-empty, null otherwise
*/
public function getOrNull() {
return $this->isEmpty() ? null : $this->get();
}

/**
* Returns true if this option is empty, false otherwise
*/
public function isEmpty() {
return $this->value === null;
}

/**
* Returns an option containing the result of applying $f to this option's value
* if it is non-empty
*
* $f should take the wrapped value and return a new value
*/
public function map(callable $f) {
return !$this->isEmpty() ? Option::just($f($this->get())) : Option::none();
}

/**
* Returns this option if it is non-empty, otherwise the given option is returned
*/
public function orElse(Option $other) {
return !$this->isEmpty() ? $this : $other;
}

/**
* Get an option from the given, possibly null, value
*/
public static function from($x) {
return new Option($x);
}

/**
* Get an option containing the given, non-null value
*/
public static function just($x) {
if( $x === null )
throw new \LogicException("Cannot create just from null value");

return new Option($x);
}

/**
* Get an empty option
*/
public static function none() {
return new Option(null);
}
}
Loading

0 comments on commit 9069086

Please sign in to comment.