protected function CaptchaWebTestBase::getMathCaptchaSolutionFromForm in CAPTCHA 8
Get the solution of the math CAPTCHA from the current form in the browser.
Parameters
null|string $form_html_id: HTML form id attribute.
Return value
int Calculated Math solution.
File
- tests/
src/ Functional/ CaptchaWebTestBase.php, line 231
Class
- CaptchaWebTestBase
- Base class for CAPTCHA tests.
Namespace
Drupal\Tests\captcha\FunctionalCode
protected function getMathCaptchaSolutionFromForm($form_html_id = NULL) {
// Get the math challenge.
if (!$form_html_id) {
$elements = $this
->xpath('//div[contains(@class, "form-item-captcha-response")]/span[@class="field-prefix"]');
}
else {
$elements = $this
->xpath('//form[@id="' . $form_html_id . '"]//div[contains(@class, "form-item-captcha-response")]/span[@class="field-prefix"]');
}
$this
->assertTrue('pass', json_encode($elements));
$challenge = (string) $elements[0];
$this
->assertTrue('pass', $challenge);
// Extract terms and operator from challenge.
$matches = [];
preg_match('/\\s*(\\d+)\\s*(-|\\+)\\s*(\\d+)\\s*=\\s*/', $challenge, $matches);
// Solve the challenge.
$a = (int) $matches[1];
$b = (int) $matches[3];
$solution = $matches[2] == '-' ? $a - $b : $a + $b;
return $solution;
}