diff --git a/src/Service/Syntax/Constraints/BooleanType/BooleanType.php b/src/Service/Syntax/Constraints/BooleanType/BooleanType.php new file mode 100644 index 0000000..2a930aa --- /dev/null +++ b/src/Service/Syntax/Constraints/BooleanType/BooleanType.php @@ -0,0 +1,15 @@ +schema())); + + if (! is_null($const = $schema->const()) && $value !== $const) { + $this->context->buildViolation($constraint->message) + ->setParameter('{{ actual }}', $this->formatValue($value)) + ->setParameter('{{ must }}', $this->formatValue($const)) + ->addViolation(); + } + } +} diff --git a/tests/Unit/Service/Syntax/Constraints/BooleanTypeTest.php b/tests/Unit/Service/Syntax/Constraints/BooleanTypeTest.php new file mode 100644 index 0000000..15695f4 --- /dev/null +++ b/tests/Unit/Service/Syntax/Constraints/BooleanTypeTest.php @@ -0,0 +1,102 @@ +validator->validate($value, $constraint); + + $this->assertNoViolation(); + } + + public static function validBooleanProvider(): array + { + return [ + [true], + [false], + ]; + } + + #[DataProvider('invalidBooleanProvider')] + public function test_invalid_boolean_values(mixed $invalidValue): void + { + $this->expectException(UnexpectedTypeException::class); + + $constraint = new BooleanType(); + $this->validator->validate($invalidValue, $constraint); + } + + public static function invalidBooleanProvider(): array + { + return [ + ['string'], + [1.4], + [1], + [new stdClass()], + [[]], + [null], + ]; + } + + public function test_violation_when_const_not_matching_value(): void + { + $constraint = new BooleanType([ + 'type' => 'boolean', + 'const' => false, + ]); + + $this->validator->validate(true, $constraint); + + $this->buildViolation($constraint->message) + ->setParameter('{{ actual }}', 'true') + ->setParameter('{{ must }}', 'false') + ->assertRaised(); + } + + public function test_valid_when_value_matches_const(): void + { + $constraint = new BooleanType([ + 'type' => 'boolean', + 'const' => false, + ]); + + $this->validator->validate(false, $constraint); + + $this->assertNoViolation(); + } + + public function test_false_value_is_valid(): void + { + $constraint = new BooleanType(); + + $this->validator->validate(false, $constraint); + + $this->assertNoViolation(); + } + + public function test_true_value_is_valid(): void + { + $constraint = new BooleanType(); + + $this->validator->validate(true, $constraint); + + $this->assertNoViolation(); + } +}