public function testValidateValueMinMax() { $val = new StringValidator(['min' => 10]); $this->assertTrue($val->validate(str_repeat('x', 10))); $this->assertFalse($val->validate('xxxx')); $val = new StringValidator(['max' => 10]); $this->assertTrue($val->validate('xxxx')); $this->assertFalse($val->validate(str_repeat('y', 20))); $val = new StringValidator(['min' => 10, 'max' => 20]); $this->assertTrue($val->validate(str_repeat('y', 15))); $this->assertFalse($val->validate('abc')); $this->assertFalse($val->validate(str_repeat('b', 25))); }
/** * Add Original Text * @param string $text * @param int $yandexSiteID * @throws InvalidParamException * @return string|bool */ public function addOriginalText($text, $yandexSiteID) { /** @var Cache $cache */ $cache = \Yii::$app->get($this->cacheComponent); $cacheKey = "Yandex_OT_sent:" . $this->clientID . "_" . $this->clientSecret; $sent = $cache->get($cacheKey); if ($sent === false) { $sent = 0; } if ($sent >= self::YANDEX_OT_DAILY_LIMIT) { throw new InvalidParamException("Daily limit exceeded!"); } $validator = new StringValidator(['min' => self::YANDEX_OT_MIN, 'max' => self::YANDEX_OT_MAX, 'enableClientValidation' => false]); if (!$validator->validate($text, $error)) { throw new InvalidParamException($error); } $text = urlencode(htmlspecialchars($text)); $text = "<original-text><content>{$text}</content></original-text>"; $response = $this->apiClient->rawApi("hosts/{$yandexSiteID}/original-texts/", "POST", $text); $success = ArrayHelper::keyExists('id', $response) && ArrayHelper::keyExists('link', $response); if ($success) { $sent++; $cache->set($cacheKey, $sent, 60 * 60 * 24); } return $success; }
/** * Updates the value of setting. * @param string[] $data * @return boolean */ public function update($data) { $validator = new StringValidator(); $validator->max = 255; foreach ($data as $key => $value) { if (!in_array($key, $this->readonly) && isset($this->settings[$key])) { if ($validator->validate($value)) { if (!$this->config->set($key, $value)) { return false; } } else { return false; } } } return true; }
/** * Validates images assigned to the page. * * @param string $attribute the attribute currently being validated * @param mixed $params the value of the "params" given in the rule */ public function validateImages($attribute, $params) { $validator = new StringValidator(); foreach ($this->{$attribute} as $image) { if (!empty($image['image']) && !$validator->validate($image['image'], $error)) { $this->addError($attribute, Yii::t('cms', 'Image must be a string.')); } } }
public function fieldTypeValidation() { // Messages $invalidMessage = "the input value has a not valid value."; // Validation by Input Type foreach ($this->fields as $field) { foreach ($field as $key => $value) { // Text if ($key === "type" && $value === "text") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // A pattern can be used if (isset($field["pattern"])) { $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]); if (!$regexValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } } // Tel if ($key === "type" && $value === "tel") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // A pattern can be used if (isset($field["pattern"])) { $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]); if (!$regexValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } else { // By default, the number must be a international phone number $phoneValidator = new PhoneValidator(); if (!$phoneValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error . ' ' . Yii::t("app", "It must has a internationally-standardized format\n (e.g. '+1 650-555-5555')")); } } } } // Url if ($key === "type" && $value === "url") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // Config validator $config = []; // A pattern can be used if (isset($field["pattern"])) { $config['pattern'] = $field["pattern"]; } $urlValidator = new UrlValidator($config); if (!$urlValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } // Color if ($key === "type" && $value === "color") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // hex color invalid if (!preg_match('/^#[a-f0-9]{6}$/i', $this->data[$field["name"]])) { $this->addError($field["name"], $field["label"], '', $invalidMessage . ' ' . Yii::t("app", "It must be a hexadecimal color string (e.g. '#FFFFFF').")); } } } // Password if ($key === "type" && $value === "password") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { $newData = trim($this->data[$field["name"]]); // Remove spaces $stringValidator = new StringValidator(['min' => 6]); if (!$stringValidator->validate($newData, $error)) { $this->addError($field["name"], $field["label"], '', $error); } // A pattern can be used if (isset($field["pattern"])) { $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]); if (!$regexValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } } // Email if ($key === "type" && $value === "email") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // Config email validator $config = []; // A pattern can be used if (isset($field["pattern"])) { $config['pattern'] = $field["pattern"]; } // Whether to check if email's domain exists and has either an A or MX record. // Be aware that this check can fail due temporary DNS problems // even if the email address is valid and an email would be deliverable if (isset($field["data-check-dns"])) { $config['checkDNS'] = true; } // Validate multiple emails separated by commas if (isset($field["multiple"])) { // Removes spaces $emails = str_replace(" ", "", $this->data[$field["name"]]); // Array of emails $emails = explode(",", $emails); if (count($emails) > 1) { $config['message'] = Yii::t('app', '{attribute} has a invalid email format: Please use a comma to separate multiple email addresses.'); } // Validate only one email address $emailValidator = new EmailValidator($config); foreach ($emails as $email) { if (!$emailValidator->validate($email, $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } else { // Validate only one email address $emailValidator = new EmailValidator($config); if (!$emailValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } } // Radio if ($key === "type" && $value === "radio") { // Only when the input value is not empty if (isset($field["name"]) && !empty($this->data[$field["name"]])) { // If no values or if the received data does not match with the form data if (empty($this->radioValues) || !in_array($this->data[$field["name"]], $this->radioValues)) { $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage); } } } // Checkbox if ($key === "type" && $value === "checkbox") { // Only when the input value is not empty if (isset($field["name"]) && !empty($this->data[$field["name"]])) { // If no values or if the received data does not match with the form data foreach ($this->data[$field["name"]] as $labelChecked) { if (empty($this->checkboxValues) || !in_array($labelChecked, $this->checkboxValues)) { $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage); } } } } // Select List if ($key === "tagName" && $value === "select") { // Only when the input value is not empty if (isset($field["name"]) && !empty($this->data[$field["name"]])) { // If no labels or if the received data does not match with the form data foreach ($this->data[$field["name"]] as $optionSelected) { if (empty($this->optionValues) || !in_array($optionSelected, $this->optionValues)) { $this->addError($field["name"], $field["label"], '', $invalidMessage); } } } } // Number & Range if ($key === "type" && $value === "number" || $key === "type" && $value === "range") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // Config number validator $config = []; // Min Number Validation (Minimum value required) if (isset($field["min"])) { $config['min'] = $field["min"]; } // Max Number Validation (Maximum value required) if (isset($field["max"])) { $config['max'] = $field["max"]; } // Only Integer Validation (Whether the attribute value can only be an integer) if (isset($field["data-integer-only"])) { $config['integerOnly'] = true; } // Pattern to Validate only Integer Numbers (The regular expression for matching integers) if (isset($field["data-integer-pattern"])) { $config['integerPattern'] = $field["data-integer-pattern"]; } // Pattern to Validate the Number (The regular expression for matching numbers) if (isset($field["data-number-pattern"])) { $config['numberPattern'] = $field["data-number-pattern"]; } $numberValidator = new NumberValidator($config); if (!$numberValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } // Date & DateTime & Time & Month & Week if ($key === "type" && $value === "date" || $key === "type" && $value === "datetime-local" || $key === "type" && $value === "time" || $key === "type" && $value === "month" || $key === "type" && $value === "week") { // Only when the input value is not empty if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") { // DateValidator Configuration array $config = []; // Date Format by default $format = "Y-m-d"; // Change Format if ($value === "datetime-local") { // DateTime Format $format = "Y-m-d\\TH:i:s"; } elseif ($value === "time") { // Time Format $format = "i:s"; } elseif ($value === "month") { // Month Format $format = "Y-m"; } elseif ($value === "week") { // First, validate by regular expression $regexValidator = new RegularExpressionValidator(['pattern' => "/\\d{4}-W\\d{2}/"]); if (!$regexValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } // Next, convert to date, to dateValidator (min / max) if (isset($field["min"])) { $config['tooSmall'] = Yii::t("app", "{attribute} must be no less than {weekMin}.", ['weekMin' => $field["min"]]); $field["min"] = date("Y-m-d", strtotime($field["min"])); } if (isset($field["max"])) { $config['tooBig'] = Yii::t("app", "{attribute} must be no greater than {weekMax}.", ['weekMax' => $field["max"]]); $field["max"] = date("Y-m-d", strtotime($field["max"])); } $this->data[$field["name"]] = date("Y-m-d", strtotime($this->data[$field["name"]])); } // Add PHP format $config['format'] = "php:" . $format; // Add Min Date Validation (The value must be later than this option) if (isset($field["min"])) { $config['min'] = $field["min"]; } // Add Max Date Validation (The value must be earlier than this option) if (isset($field["max"])) { $config['max'] = $field["max"]; } $dateValidator = new DateValidator($config); if (!$dateValidator->validate($this->data[$field["name"]], $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } // File if ($key === "type" && $value === "file") { // Only when the $_FILES name value is not empty if (isset($field["name"]) && isset($_FILES[$field["name"]]['name']) && !empty($_FILES[$field["name"]]['name'])) { // Config FileValidator $config = []; // File type validation // Note that you should enable fileinfo PHP extension. if (isset($field["accept"]) && extension_loaded('fileinfo')) { // Removes dots $extensions = str_replace(".", "", $field["accept"]); // Removes spaces $extensions = str_replace(" ", "", $extensions); $config['extensions'] = explode(",", $extensions); } // File Min Size validation if (isset($field["data-min-size"])) { // Removes dots $config['minSize'] = (int) $field["data-min-size"]; } // File Min Size validation if (isset($field["data-max-size"])) { // Removes dots $config['maxSize'] = (int) $field["data-max-size"]; } $file = UploadedFile::getInstanceByName($field["name"]); $fileValidator = new FileValidator($config); if (!$fileValidator->validate($file, $error)) { $this->addError($field["name"], $field["label"], '', $error); } } } } } }
/** * @return User */ private function createAdminUser() { $name = $this->prompt("Введите имя суперпользовтаеля системы", ['default' => 'admin']); $password = $this->prompt("Введите пароль суперпользователя системы:", ['required' => true, 'validator' => function ($input) { $validator = new StringValidator(['min' => 6]); return $validator->validate($input); }]); $user = new User(); $user->username = $name; $user->setPassword($password); $user->status = User::STATUS_ACTIVE; $user->email = Yii::$app->params['email.admin']; $user->generateAuthKey(); $user->save(); return $user; }
/** * @return User */ private function createAdminUser() { $password = $this->prompt("Введите пароль суперпользователя системы:", ['required' => true, 'validator' => function ($input) { $validator = new StringValidator(['min' => 6]); return $validator->validate($input); }]); $user = new User(); $user->username = Yii::$app->params['admin.name']; $user->setPassword($password); $user->email = Yii::$app->params['admin.email']; $user->generateAuthKey(); $user->save(); return $user; }