Skip to content

Commit c3474b6

Browse files
committed
Add boolean rule
1 parent 67be35e commit c3474b6

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

src/Rules/Boolean.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace IgniteKit\Validation\Rules;
4+
5+
use IgniteKit\Validation\Rule;
6+
7+
class Boolean extends Rule
8+
{
9+
/**
10+
* @var string
11+
*/
12+
protected $message = "The :attribute must be a boolean";
13+
14+
/**
15+
* Check the value is valid
16+
*
17+
* @param mixed $value
18+
* @return bool
19+
* @throws \Exception
20+
*/
21+
public function check($value): bool
22+
{
23+
return \in_array($value, [\true, \false, "true", "false", 1, 0, "0", "1", "y", "n"], \true);
24+
}
25+
}

src/Validator.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ protected function registerBaseValidators()
138138
'between' => new Rules\Between,
139139
'url' => new Rules\Url,
140140
'integer' => new Rules\Integer,
141+
'boolean' => new Rules\Boolean,
141142
'ip' => new Rules\Ip,
142143
'ipv4' => new Rules\Ipv4,
143144
'ipv6' => new Rules\Ipv6,

tests/Rules/BooleanTest.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
namespace IgniteKit\Validation\Tests;
4+
5+
use IgniteKit\Validation\Rules\Boolean;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class BooleanTest extends TestCase
9+
{
10+
public function setUp():void
11+
{
12+
$this->rule = new Boolean;
13+
}
14+
15+
public function testValids()
16+
{
17+
$this->assertTrue($this->rule->check(\true));
18+
$this->assertTrue($this->rule->check(\false));
19+
$this->assertTrue($this->rule->check(1));
20+
$this->assertTrue($this->rule->check(0));
21+
$this->assertTrue($this->rule->check('1'));
22+
$this->assertTrue($this->rule->check('0'));
23+
$this->assertTrue($this->rule->check('y'));
24+
$this->assertTrue($this->rule->check('n'));
25+
}
26+
27+
public function testInvalids()
28+
{
29+
$this->assertFalse($this->rule->check(11));
30+
$this->assertFalse($this->rule->check([]));
31+
$this->assertFalse($this->rule->check('foo123'));
32+
$this->assertFalse($this->rule->check('123foo'));
33+
$this->assertFalse($this->rule->check([123]));
34+
$this->assertFalse($this->rule->check('123.456'));
35+
$this->assertFalse($this->rule->check('-123.456'));
36+
}
37+
}

0 commit comments

Comments
 (0)