2016-09-03 04:24:22 +05:30
|
|
|
<?php
|
|
|
|
namespace common\validators;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use Ramsey\Uuid\Uuid;
|
|
|
|
use yii\validators\Validator;
|
|
|
|
|
|
|
|
class UuidValidator extends Validator {
|
|
|
|
|
2016-11-04 22:03:57 +05:30
|
|
|
public $allowNil = true;
|
|
|
|
|
2016-09-03 04:24:22 +05:30
|
|
|
public $skipOnEmpty = false;
|
|
|
|
|
|
|
|
public $message = '{attribute} must be valid uuid';
|
|
|
|
|
|
|
|
public function validateAttribute($model, $attribute) {
|
|
|
|
try {
|
|
|
|
$uuid = Uuid::fromString($model->$attribute)->toString();
|
|
|
|
$model->$attribute = $uuid;
|
|
|
|
} catch (InvalidArgumentException $e) {
|
|
|
|
$this->addError($model, $attribute, $this->message, []);
|
|
|
|
}
|
2016-11-04 22:03:57 +05:30
|
|
|
|
|
|
|
if (isset($uuid) && $this->allowNil === false && $uuid === Uuid::NIL) {
|
|
|
|
$this->addError($model, $attribute, $this->message, []);
|
|
|
|
}
|
2016-09-03 04:24:22 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
}
|