-
Notifications
You must be signed in to change notification settings - Fork 18
/
AutonumberValidator.php
117 lines (103 loc) · 2.77 KB
/
AutonumberValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace mdm\autonumber;
use yii\db\ActiveRecord;
use yii\validators\Validator;
/**
* Validator use to fill autonumber
*
* Use to fill attribute with formatet autonumber.
*
* Usage at [[$owner]] rules()
*
* ~~~
* return [
* [['sales_num'], 'autonumber', 'format'=>'SA.'.date('Ymd').'?'],
* ...
* ]
* ~~~
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class AutonumberValidator extends Validator
{
/**
* @var mixed the default value or a PHP callable that returns the default value which will
* be assigned to the attributes being validated if they are empty. The signature of the PHP callable
* should be as follows,
*
* ```php
* function foo($model, $attribute) {
* // compute value
* return $value;
* }
* ```
*
* @see [[Behavior::$value]]
*/
public $format;
/**
* @var integer digit number of auto number
*/
public $digit;
/**
* @var mixed
*/
public $group;
/**
* @var bool
*/
public $alnum;
/**
* @var boolean
*/
public $unique = true;
/**
* @inheritdoc
*/
public $skipOnEmpty = false;
/**
* @var boolean
*/
public $throwIsStale = false;
/**
* @var array
*/
private static $_executed = [];
/**
* @inheritdoc
*/
public function validateAttribute($object, $attribute)
{
if ($this->isEmpty($object->$attribute)) {
$eventId = uniqid();
$object->on(ActiveRecord::EVENT_BEFORE_INSERT, [$this, 'beforeSave'], [$eventId, $attribute]);
$object->on(ActiveRecord::EVENT_BEFORE_UPDATE, [$this, 'beforeSave'], [$eventId, $attribute]);
}
}
/**
* Handle for [[\yii\db\ActiveRecord::EVENT_BEFORE_INSERT]] and [[\yii\db\ActiveRecord::EVENT_BEFORE_UPDATE]]
* @param \yii\base\ModelEvent $event
*/
public function beforeSave($event)
{
list($id, $attribute) = $event->data;
if (isset(self::$_executed[$id])) {
return;
}
/* @var $object \yii\db\ActiveRecord */
$object = $event->sender;
if (is_string($this->format) && method_exists($object, $this->format)) {
$value = call_user_func([$object, $this->format], $object, $attribute);
} else {
$value = is_callable($this->format) ? call_user_func($this->format, $object, $attribute) : $this->format;
}
$group = [
'class' => $this->unique ? get_class($object) : false,
'group' => $this->group,
'attribute' => $attribute,
];
$object->$attribute = AutoNumber::generate($value, $this->alnum, $this->digit, $group);
self::$_executed[$id] = true;
}
}