Completed
Push — master ( 326182...c37a35 )
by Xu
05:59 queued 26s
created

SnowflakeBehavior::init()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.tintsoft.com/
4
 * @copyright Copyright (c) 2012 TintSoft Technology Co. Ltd.
5
 * @license http://www.tintsoft.com/license/
6
 */
7
8
namespace yuncms\behaviors;
9
10
use yii\base\InvalidConfigException;
11
use yii\behaviors\AttributeBehavior;
12
use yii\db\BaseActiveRecord;
13
use yii\di\Instance;
14
use yuncms\base\Snowflake;
15
16
/**
17
 * Class SnowflakeBehavior
18
 *
19
 * @author Tongle Xu <[email protected]>
20
 * @since 3.0
21
 */
22
class SnowflakeBehavior extends AttributeBehavior
23
{
24
    /**
25
     * @var string
26
     */
27
    public $attribute = 'id';
28
29
    /**
30
     * @inheritdoc
31
     */
32
    public $value;
33
34
    /**
35
     * @var string|Snowflake
36
     */
37
    protected $snowflake = 'snowflake';
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function init()
43
    {
44
        parent::init();
45
        if (empty($this->attributes)) {
46
            $this->attributes = [BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->attribute],];
47
        }
48
        if ($this->attribute === null) {
49
            throw new InvalidConfigException('Either "attribute" property must be specified.');
50
        }
51
        $this->snowflake = Instance::ensure($this->snowflake, 'yuncms\base\Snowflake');
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    protected function getValue($event)
58
    {
59
        if ($this->value === null) {
60
            return $this->snowflake->next();
61
        }
62
        return parent::getValue($event);
63
    }
64
}