Skip to content

Commit

Permalink
TypeChecker::boolean add option for strict comparison (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
gam6itko committed Nov 23, 2023
1 parent 8fc21d0 commit f3c06ad
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Checker/TypeChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,12 @@ public function notNull(mixed $value): bool
/**
* Value has to be boolean or integer[0,1].
*/
public function boolean(mixed $value): bool
public function boolean(mixed $value, bool $strict = false): bool
{
return \is_bool($value) || (\is_numeric($value) && ($value === 0 || $value === 1));
if (\is_bool($value)) {
return true;
}

return false === $strict && (\is_numeric($value) && ($value === 0 || $value === 1));
}
}
15 changes: 15 additions & 0 deletions tests/src/Unit/Checkers/TypesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,19 @@ public function testBoolean(): void
$this->assertFalse($checker->boolean('0'));
$this->assertFalse($checker->boolean('1'));
}

public function testBooleanStrict(): void
{
$checker = new TypeChecker();

$this->assertTrue($checker->boolean(true, true));
$this->assertTrue($checker->boolean(false, true));

$this->assertFalse($checker->boolean(1, true));
$this->assertFalse($checker->boolean(0, true));
$this->assertFalse($checker->boolean('true', true));
$this->assertFalse($checker->boolean('false', true));
$this->assertFalse($checker->boolean('0', true));
$this->assertFalse($checker->boolean('1', true));
}
}

0 comments on commit f3c06ad

Please sign in to comment.