Completed
Push — master ( bb2114...3df708 )
by Dave
9s
created

Maybe.php ➔ maybe()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 4
rs 10
1
<?php
2
3
namespace DaveRoss\FunctionalProgrammingUtils;
4
5
/**
6
 * Class Maybe
7
 * @package DaveRoss\FunctionalProgrammingUtils
8
 */
9
class Maybe extends Monad
10
{
11
12
    /**
13
     * Apply a function to this Monad's value only if the value is not null
14
     *
15
     * @param callable $f
16
     *
17
     * @return Maybe
18
     */
19
    public function map(callable $f)
20
    {
21
        return ( $this->isNothing() ) ? Maybe::of(null) : Maybe::of($f( $this->value ));
22
    }
23
24
    public function isNothing()
25
    {
26
        return ( null == $this->value );
27
    }
28
}
29
30
/**
31
 * Helper function to apply a function to a Maybe that is not Maybe(null). Returns the value directly rather
32
 * than wrapping it in another Maybe.
33
 *
34
 * @param mixed    $x default value
35
 * @param callable $f function to apply to a non-empty Maybe's value
36
 * @param Maybe    $m the Maybe to run the function against if the Maybe is not Maybe(null)
37
 *
38
 * @return mixed
39
 */
40
function maybe($x, callable $f, Maybe $m)
41
{
42
    return ( $m->isNothing() ) ? $x : $f( $m->value() );
43
}