Skip to content

Commit

Permalink
add option, optional functions
Browse files Browse the repository at this point in the history
  • Loading branch information
nishimura committed Feb 17, 2017
1 parent 86334c4 commit 1b4f2a3
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/Filter.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php
declare(strict_types=1);

namespace Laiz\Filter;

Expand Down
28 changes: 28 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,31 @@ function max($n)
return new Result\Error($state, "Error max: Input [$input] is over than [$n]");
});
}

// String -> Filter s String o -> Filter s String o
function option(...$args)
{
return f(function(string $default, Filter $m): Filter {
return new Filter(function(array $si) use ($default, $m){
list($state, $input) = $si;
if ($input === '')
return ($m->unFilter())([$state, $default]);
else
return ($m->unFilter())($si);
});
}, ...$args);
}

// Filter s String o -> Filter s String o
function optional(...$args)
{
return f(function(Filter $m): Filter{
return new Filter(function(array $si) use ($m){
list($state, $input) = $si;
if ($input === '')
return new Result\EmptyOk();
else
return ($m->unFilter())($si);
});
}, ...$args);
}
30 changes: 27 additions & 3 deletions test/src/FilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use function Laiz\Filter\runFilter;
use function Laiz\Filter\filterPure;
use function Laiz\Filter\combine;
use function Laiz\Filter\{toInt, toId, min, max};
use function Laiz\Filter\{toInt, toId, min, max, option, optional};
use Laiz\Filter;

class FilterTest extends \PHPUnit\Framework\TestCase
Expand Down Expand Up @@ -64,7 +64,7 @@ public function testToInt()
public function testToIntException(){
$m = toInt();
$ret = runFilter($m, 3);
$this->assertFail('3 is not string');
$this->fail('3 is not string');
}

public function testMin()
Expand Down Expand Up @@ -120,6 +120,30 @@ public function testCombineTypeError()
$validator = max(255);
$m = combine($converter, $validator);
$ret = runFilter($m, 3);
$this->assertFail('3 is not string');
$this->fail('3 is not string');
}

public function testOption()
{
$m = option('999', toInt());
$ret = runFilter($m, '5');
$this->assertSame(5, $ret->result());
$this->assertSame('5', $ret->state());

$ret = runFilter($m, '');
$this->assertSame(999, $ret->result());
$this->assertSame('', $ret->state());
}

public function testOptional()
{
$m = optional(toInt());
$ret = runFilter($m, '5');
$this->assertSame(5, $ret->result());
$this->assertSame('5', $ret->state());

$ret = runFilter($m, '');
$this->assertInstanceOf(Filter\Result\EmptyOk::class, $ret);
}

}

0 comments on commit 1b4f2a3

Please sign in to comment.