Browse Source

Merge pull request #10638 from githubjeka/10263

Bug: `yii\validators\UniqueValidator` doesn't work when `targetClass` is specified as class from global scope of namespace .
tags/2.0.7
Dmitry Naumenko 9 years ago
parent
commit
c9580b5ba4
  1. 2
      framework/validators/UniqueValidator.php
  2. 42
      tests/framework/validators/UniqueValidatorTest.php

2
framework/validators/UniqueValidator.php

@ -106,7 +106,7 @@ class UniqueValidator extends Validator
$query->andWhere($this->filter);
}
if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass) {
if (!$model instanceof ActiveRecordInterface || $model->getIsNewRecord() || $model->className() !== $targetClass::className()) {
// if current $model isn't in the database yet then it's OK just to call exists()
// also there's no need to run check based on primary keys, when $targetClass is not the same as $model's class
$exists = $query->exists();

42
tests/framework/validators/UniqueValidatorTest.php

@ -171,4 +171,44 @@ class UniqueValidatorTest extends DatabaseTestCase
$val->validateAttribute($m, 'description');
$this->assertTrue($m->hasErrors('description'));
}
}
public function testValidateScopeNamespaceTargetClassForNewClass()
{
$validator = new UniqueValidator();
/** @var Profile $profileModel */
$profileModel = new Profile(['description'=>'profile customer 1']);
$validator->validateAttribute($profileModel, 'description');
$this->assertTrue($profileModel->hasErrors('description'));
$profileModel->clearErrors();
$validator->targetClass = 'yiiunit\data\ar\Profile';
$validator->validateAttribute($profileModel, 'description');
$this->assertTrue($profileModel->hasErrors('description'));
$profileModel->clearErrors();
$validator->targetClass = '\yiiunit\data\ar\Profile';
$validator->validateAttribute($profileModel, 'description');
$this->assertTrue($profileModel->hasErrors('description'));
}
public function testValidateScopeNamespaceTargetClass()
{
$validator = new UniqueValidator();
/** @var Profile $profileModel */
$profileModel = Profile::findOne(1);
$validator->validateAttribute($profileModel, 'description');
$this->assertFalse($profileModel->hasErrors('description'));
$profileModel->clearErrors();
$validator->targetClass = 'yiiunit\data\ar\Profile';
$validator->validateAttribute($profileModel, 'description');
$this->assertFalse($profileModel->hasErrors('description'));
$profileModel->clearErrors();
$validator->targetClass = '\yiiunit\data\ar\Profile';
$validator->validateAttribute($profileModel, 'description');
$this->assertFalse($profileModel->hasErrors('description'));
}
}
Loading…
Cancel
Save