/** * Initializes the object. * This method is invoked at the end of the constructor after the object is initialized with the * given configuration. */ public function init() { parent::init(); if ($this->uniqueValidatorClassName === null) { $this->uniqueValidatorClassName = UniqueValidator::className(); } }
/** * Checks if given slug value is unique. * @param string $slug slug value * @return boolean whether slug is unique. */ protected function validateSlug($slug) { /* @var $validator UniqueValidator */ /* @var $model BaseActiveRecord */ $validator = Yii::createObject(array_merge(['class' => UniqueValidator::className()], $this->uniqueValidator)); $model = clone $this->owner; $model->clearErrors(); $model->{$this->slugAttribute} = $slug; $validator->validateAttribute($model, $this->slugAttribute); return !$model->hasErrors(); }
/** * Validate SEO URL and ensure its uniqueness. */ private function _validateUrlField() { if (empty($this->urlField)) { // If do not need to work with SEO:url, then skip further work return; } $model = $this->owner; // Add UNIQUE validator for SEO:url field $validator = Validator::createValidator(UniqueValidator::className(), $model, $this->urlField, ['filter' => $this->uniqueUrlFilter]); // If SEO: url is not filled by the user, then generate its value $urlFieldVal = trim((string) $model->{$this->urlField}); if ($urlFieldVal === '') { $urlFieldVal = $this->_getProduceValue($this->urlProduceField); } // Transliterated string and remove from it the extra characters $seoUrl = $this->_getSeoName($urlFieldVal, $this->maxUrlLength, $this->toLowerSeoUrl); // If there is a match with banned names, then add to the url underbar // to the end while (in_array($seoUrl, $this->stopNames)) { $seoUrl .= '_'; } $model->{$this->urlField} = $seoUrl; // Start the first unique validation $validator->validateAttribute($model, $this->urlField); // Run the validation of up to 50 times, until there is a unique SEO:url // name $i = 0; while ($model->hasErrors($this->urlField)) { // Remove the error message received in the last validation $model->clearErrors($this->urlField); // If failed 50 times, then something went wrong... if (++$i > 50) { // We establish SEO: url to a random hash $model->{$this->urlField} = md5(uniqid()); // Finish "infinite" loop break; } // Add "_" at the end of SEO:url $newSeoUrl = $model->{$this->urlField} . '_'; $model->{$this->urlField} = $newSeoUrl; // Run the validator again, because in the previous line, we changed // the value of adding a suffix $validator->validateAttribute($model, $this->urlField); } }