Completed
Push — master ( f95aab...ce10dc )
by Basil
04:32
created

TimestampBehavior::beforeInsert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace luya\behaviors;
4
5
use yii\base\Behavior;
6
use yii\db\ActiveRecord;
7
8
/**
9
 * Timestamp Behavior.
10
 *
11
 * Set the unix timestamp for given update and/or insert fields.
12
 *
13
 * ```php
14
 * 'timestamp' => [
15
 *     'class' => \luya\behaviors\Timestamp::class,
16
 *     'insert' => ['last_update'],
17
 *     'update' => ['last_update'],
18
 * ]
19
 * ```
20
 *
21
 * @author Basil Suter <[email protected]>
22
 * @since 1.0.0
23
 */
24
class TimestampBehavior extends Behavior
25
{
26
    /**
27
     * @var array An array with all fields where the timestamp should be applied to on insert.
28
     */
29
    public $insert = [];
30
    
31
    /**
32
     * @var array An array with all fields where the timestamp should be applied to on update.
33
     */
34
    public $update = [];
35
    
36
    /**
37
     * Register event handlers before insert and update.
38
     *
39
     * @see \yii\base\Behavior::events()
40
     */
41
    public function events()
42
    {
43
        return [
44
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
45
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
46
        ];
47
    }
48
    
49
    /**
50
     * Insert the timestamp for all provided fields.
51
     *
52
     * @param \yii\base\Event $event Event object from Active Record.
53
     */
54
    public function beforeInsert($event)
55
    {
56
        foreach ($this->insert as $field) {
57
            $event->sender->$field = time();
58
        }
59
    }
60
    
61
    /**
62
     * Update the timestamp for all provided fields.
63
     *
64
     * @param \yii\base\Event $event Event object from Active Record.
65
     */
66
    public function beforeUpdate($event)
67
    {
68
        foreach ($this->update as $field) {
69
            $event->sender->$field = time();
70
        }
71
    }
72
}
73