forked from mdmsoft/yii2-autonumber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Behavior.php
122 lines (109 loc) · 3 KB
/
Behavior.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
118
119
120
121
122
<?php
namespace bahirul\yii2\autonumber;
use yii\db\StaleObjectException;
use yii\db\BaseActiveRecord;
use Exception;
/**
* Behavior use to generate formated autonumber.
* Use at ActiveRecord behavior
*
* ~~~
* public function behavior()
* {
* return [
* ...
* [
* 'class' => 'mdm\autonumber\Behavior',
* 'value' => date('Ymd').'.?', // ? will replace with generated number
* 'digit' => 6, // specify this if you need leading zero for number
* ]
* ]
* }
* ~~~
*
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
* @since 1.0
*/
class Behavior extends \yii\behaviors\AttributeBehavior
{
/**
* @var integer digit number of auto number
*/
public $digit;
/**
* @var mixed Optional.
*/
public $group;
/**
* @var boolean If set `true` number will genarate unique for owner classname.
* Default `true`.
*/
public $unique = true;
/**
* @var string
*/
public $attribute;
/**
* [$db description]
*
* @var \yii\db\Connection or NULL
*/
public $db;
/**
* @inheritdoc
*/
public function init()
{
if ($this->attribute !== null) {
$this->attributes[BaseActiveRecord::EVENT_BEFORE_INSERT][] = $this->attribute;
}
parent::init();
}
/**
* @inheritdoc
*/
protected function getValue($event)
{
if (is_string($this->value) && method_exists($this->owner, $this->value)) {
$value = call_user_func([$this->owner, $this->value], $event);
} else {
$value = is_callable($this->value) ? call_user_func($this->value, $event) : $this->value;
}
$group = md5(serialize([
'class' => $this->unique ? get_class($this->owner) : false,
'group' => $this->group,
'attribute' => $this->attribute,
]));
do {
$repeat = false;
try {
//set AutoNumber db conn
AutoNumber::setDbConn($this->db);
$model = AutoNumber::findOne($group);
if ($model) {
$number = $model->number + 1;
} else {
$model = new AutoNumber([
'group' => $group
]);
$model->dbConn = $this->db;
$number = 1;
}
$model->update_time = time();
$model->number = $number;
$model->save(false);
} catch (Exception $exc) {
if ($exc instanceof StaleObjectException) {
$repeat = true;
} else {
throw $exc;
}
}
} while ($repeat);
if ($value === null) {
return $number;
} else {
return str_replace('?', $this->digit ? sprintf("%0{$this->digit}d", $number) : $number, $value);
}
}
}