Skip to content

Commit 96a14b6

Browse files
committed
Handling optionals created with nulls.
1 parent 56ec025 commit 96a14b6

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

source/Optional.php

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,13 @@ public function __construct($value)
3131
*/
3232
public function value(callable $then = null)
3333
{
34-
if (is_callable($then)) {
35-
$then($this->value);
36-
}
34+
if ($this->isNotNone($this->value)) {
35+
if (is_callable($then)) {
36+
$then($this->value);
37+
}
3738

38-
return $this->value;
39+
return $this->value;
40+
}
3941
}
4042

4143
/**
@@ -54,9 +56,9 @@ public function __call($method, $parameters)
5456
if ($this->isNotNone($result)) {
5557
return new Optional($result);
5658
}
57-
}
5859

59-
return new None();
60+
return new None();
61+
}
6062
}
6163

6264
/**
@@ -87,6 +89,11 @@ protected function isNotNone($result)
8789
*/
8890
public function none(callable $then = null)
8991
{
92+
if (!$this->isNotNone($this->value)) {
93+
$then();
94+
return;
95+
}
96+
9097
return $this;
9198
}
9299
}

tests/OptionalTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,26 @@ public function itSquashesNestedOptionals()
113113
$optional->value()
114114
);
115115
}
116+
117+
/**
118+
* @test
119+
*
120+
* @return void
121+
*/
122+
public function itHandlesOptionalsCreatedWithNulls()
123+
{
124+
$optional = new Optional(null);
125+
126+
$optional->value(function() {
127+
$this->fail("Value should not be called here.");
128+
});
129+
130+
$flag = false;
131+
132+
$optional->none(function() use (&$flag) {
133+
$flag = true;
134+
});
135+
136+
$this->assertTrue($flag);
137+
}
116138
}

0 commit comments

Comments
 (0)