Skip to content

Commit

Permalink
Added option to accept true and false strings
Browse files Browse the repository at this point in the history
as valid bools
  • Loading branch information
eldadfux committed Jun 21, 2020
1 parent ca2ebe3 commit a5feacb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
23 changes: 20 additions & 3 deletions src/Validator/Boolean.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@
*/
class Boolean extends Validator
{
/**
* @var bool
*/
protected $strings = false;

/**
* @param array $strings
*/
public function __construct(bool $strings = false)
{
$this->strings = $strings;
}

/**
* Get Description
*
Expand All @@ -46,10 +59,14 @@ public function getDescription()
*/
public function isValid($value)
{
if (!\is_bool($value)) {
return false;
if($this->strings && ($value === 'true' || $value === 'false')) {
return true;
}

if (\is_bool($value)) {
return true;
}

return true;
return false;
}
}
17 changes: 15 additions & 2 deletions tests/Validator/BooleanTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ class BooleanTest extends TestCase

public function setUp()
{
$this->boolean = new Boolean();
}

public function tearDown()
Expand All @@ -34,9 +33,23 @@ public function tearDown()

public function testIsValid()
{
// Assertions
$this->boolean = new Boolean();

$this->assertEquals(true, $this->boolean->isValid(true));
$this->assertEquals(true, $this->boolean->isValid(false));
$this->assertEquals(false, $this->boolean->isValid('false'));
$this->assertEquals(false, $this->boolean->isValid('true'));
$this->assertEquals(false, $this->boolean->isValid(['string', 'string']));
$this->assertEquals(false, $this->boolean->isValid('string'));
$this->assertEquals(false, $this->boolean->isValid(1));
$this->assertEquals(false, $this->boolean->isValid(1.2));

$this->boolean = new Boolean(true);

$this->assertEquals(true, $this->boolean->isValid(true));
$this->assertEquals(true, $this->boolean->isValid(false));
$this->assertEquals(true, $this->boolean->isValid('false'));
$this->assertEquals(true, $this->boolean->isValid('true'));
$this->assertEquals(false, $this->boolean->isValid(['string', 'string']));
$this->assertEquals(false, $this->boolean->isValid('string'));
$this->assertEquals(false, $this->boolean->isValid(1));
Expand Down

0 comments on commit a5feacb

Please sign in to comment.