/** * {@inheritdoc} * * @param Validation $validation * @param string $attribute * * @return bool */ public function validate(Validation $validation, $attribute) { $secret = $this->getOption('secret'); $value = $validation->getValue($attribute); $request = $validation->getDI()->get('request'); $remoteIp = $request->getClientAddress(false); if (!empty($value)) { $curl = curl_init(self::RECAPTCHA_URL); curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => ['secret' => $secret, 'response' => $value, 'remoteip' => $remoteIp]]); $response = json_decode(curl_exec($curl), true); curl_close($curl); } if (empty($response['success'])) { $label = $this->getOption('label'); if (empty($label)) { $label = $validation->getLabel($attribute); } $message = $this->getOption('message'); $replacePairs = [':field', $label]; if (empty($message) && !empty($response['error-codes'])) { $message = $this->messages[$response['error-codes']]; } if (empty($message)) { $message = $validation->getDefaultMessage('ReCaptcha'); } $validation->appendMessage(new Message(strtr($message, $replacePairs), $attribute, 'ReCaptcha')); return false; } return true; }
public function validate(Validation $validator, $attribute) { $message = $this->getOption('message'); $table = $validator->getEntity()->getSource(); $di = $validator->getDI(); if (strpos($attribute, '|') == 0) { $value = $validator->getValue($attribute); if (!$message) { $message = '您填写的' . $attribute . '已经被注册'; } $stmt = $di['db']->prepare("SELECT COUNT(*) FROM {$table} WHERE {$attribute}=:value"); $stmt->bindValue(':value', $value); } else { $attribute = explode('|', $attribute); $sql = "SELECT COUNT(*) FROM {$table} WHERE "; for ($i = 0; $i < count($attribute); $i++) { $a = $attribute[$i]; if ($i != count($attribute) - 1) { $sql .= "{$a}=? AND "; } else { $sql .= "{$a}=?"; } } $stmt = $di['db']->prepare($sql); for ($i = 0; $i < count($attribute); $i++) { $value = $validator->getValue($attribute[$i]); $stmt->bindValue($i + 1, $value); } } $stmt->execute(); $result = $stmt->fetch(\PDO::FETCH_NUM); if ($result[0] == 1) { $validator->appendMessage(new Message($message, $attribute)); return false; } return true; }