Skip to content

Commit

Permalink
Add error code to Recaptcha cosntraint
Browse files Browse the repository at this point in the history
  • Loading branch information
glaubinix committed Mar 13, 2024
1 parent 6db1a17 commit b2b9c7f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
6 changes: 6 additions & 0 deletions src/Validator/Constraints/Recaptcha2.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@
*/
final class Recaptcha2 extends Constraint
{
public const INVALID_RECAPTCHA_ERROR = 'b2c483cd-90b6-4810-aa45-fd615e89f046';

protected const ERROR_NAMES = [
self::INVALID_RECAPTCHA_ERROR => 'INVALID_RECAPTCHA_ERROR',
];

public string $message = 'Invalid ReCaptcha.';

public function validatedBy(): string
Expand Down
5 changes: 4 additions & 1 deletion src/Validator/Constraints/Recaptcha2Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ public function validate(mixed $value, Constraint $constraint): void
try {
$this->verifier->verify($value);
} catch (RecaptchaException) {
$this->context->addViolation($constraint->message);
$this->context
->buildViolation($constraint->message)
->setCode(Recaptcha2::INVALID_RECAPTCHA_ERROR)
->addViolation();
}
}
}
6 changes: 3 additions & 3 deletions tests/Validator/Constraints/Recaptcha2ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function testValidateShouldThrowException(): void
$exception = new RecaptchaException($response);
$constraint = new Recaptcha2();
$this->verifier->expects(self::once())->method('verify')->will(self::throwException($exception));
$this->context->expects(self::once())->method('addViolation');
$this->context->expects(self::once())->method('buildViolation');

$this->validator->validate('dummy', $constraint);
}
Expand All @@ -45,7 +45,7 @@ public function testValidateShouldNotThrowException(): void
{
$constraint = new Recaptcha2();
$this->verifier->expects(self::once())->method('verify');
$this->context->expects(self::never())->method('addViolation');
$this->context->expects(self::never())->method('buildViolation');

$this->validator->validate('dummy', $constraint);
}
Expand All @@ -54,7 +54,7 @@ public function testValidateShouldAcceptEmptyValues(): void
{
$constraint = new Recaptcha2();
$this->verifier->expects(self::once())->method('verify');
$this->context->expects(self::never())->method('addViolation');
$this->context->expects(self::never())->method('buildViolation');

$this->validator->validate(null, $constraint);
}
Expand Down

0 comments on commit b2b9c7f

Please sign in to comment.