captchaHelper = $captchaHelper; $this->captchaStringResolver = $captchaStringResolver; $this->currentUser = $currentUser; $this->customerRepository = $customerRepository; } /** * Entry point for captcha validation * * @param RequestInterface $request * @throws LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function validateSending(RequestInterface $request): void { $this->validateCaptcha($request); } /** * Validates captcha and triggers log attempt * * @param RequestInterface $request * @throws LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ private function validateCaptcha(RequestInterface $request): void { $captchaTargetFormName = 'product_sendtofriend_form'; /** @var DefaultModel $captchaModel */ $captchaModel = $this->captchaHelper->getCaptcha($captchaTargetFormName); if ($captchaModel->isRequired()) { $word = $this->captchaStringResolver->resolve( $request, $captchaTargetFormName ); $isCorrectCaptcha = $captchaModel->isCorrect($word); if (!$isCorrectCaptcha) { $this->logCaptchaAttempt($captchaModel); throw new LocalizedException(__('Incorrect CAPTCHA')); } } $this->logCaptchaAttempt($captchaModel); } /** * Log captcha attempts * * @param DefaultModel $captchaModel * @throws LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ private function logCaptchaAttempt(DefaultModel $captchaModel): void { $email = ''; if ($this->currentUser->getUserType() == UserContextInterface::USER_TYPE_CUSTOMER) { $email = $this->customerRepository->getById($this->currentUser->getUserId())->getEmail(); } $captchaModel->logAttempt($email); } }