-
Notifications
You must be signed in to change notification settings - Fork 18
/
Behavior.php
85 lines (76 loc) · 1.89 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
<?php
namespace mdm\autonumber;
use yii\behaviors\AttributeBehavior;
use yii\db\BaseActiveRecord;
/**
* Behavior use to generate formated autonumber.
* Use at ActiveRecord behavior
*
* ~~~
* public function behavior()
* {
* return [
* ...
* [
* 'class' => 'mdm\autonumber\Behavior',
* 'value' => 'INV-{Ymd}-????', // ? will replace with generated number
* ]
* ]
* }
* ~~~
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class Behavior extends 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;
/**
*
* @var bool If set `true` formated number will return alfabet and numeric.
*/
public $alnum = false;
/**
* @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 = [
'class' => $this->unique ? get_class($this->owner) : false,
'group' => $this->group,
'attribute' => $this->attribute,
];
return AutoNumber::generate($value, $this->alnum, $this->digit, $group);
}
}