Completed
Push — master ( 2fa9a1...638976 )
by vistart
09:20
created

TimestampTrait::removeIfExpired()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 12.4085

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
ccs 3
cts 9
cp 0.3333
rs 8.8571
cc 5
eloc 7
nc 3
nop 0
crap 12.4085
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use Closure;
16
use yii\behaviors\TimestampBehavior;
17
18
/**
19
 * Entity features concerning timestamp.
20
 * @property-read array $timestampBehaviors
21
 * @property-read string|int createdAt
22
 * @property-read string|int updatedAt
23
 * @property-read array $createdAtRules
24
 * @property-read array $updatedAtRules
25
 * @property-read boolean isExpired
26
 * @version 2.0
27
 * @author vistart <[email protected]>
28
 */
29
trait TimestampTrait
30
{
31
32
    /**
33
     * @var string the attribute that will receive datetime value
34
     * Set this property to false if you do not want to record the creation time.
35
     */
36
    public $createdAtAttribute = 'create_time';
37
38
    /**
39
     * @var string the attribute that will receive datetime value.
40
     * Set this property to false if you do not want to record the update time.
41
     */
42
    public $updatedAtAttribute = 'update_time';
43
44
    /**
45
     * @var integer Determine the format of timestamp.
46
     */
47
    public $timeFormat = 0;
48
    public static $timeFormatDatetime = 0;
49
    public static $timeFormatTimestamp = 1;
50
    public static $initDatetime = '1970-01-01 00:00:00';
51
    public static $initTimestamp = 0;
52
53
    /**
54
     * @var int|false the expiration in seconds, or false if it will not be expired.
55
     */
56
    public $expiredAt = false;
57
58
    /**
59
     * @var Closure
60
     */
61
    public $expiredRemovingCallback;
62
    public static $eventExpiredRemoved = 'expiredRemoved';
63
64
    /**
65
     * Check this entity whether expired.
66
     * @return boolean
67
     */
68 48
    public function getIsExpired()
69
    {
70 48
        $createdAt = $this->createdAt;
71 48
        if ($this->expiredAt === false || $createdAt === null) {
72 48
            return false;
73
        }
74 2
        return $this->offsetDatetime(-(int) $this->expiredAt) > $createdAt;
75
    }
76
77
    /**
78
     * Remove myself if expired.
79
     * @return boolean
80
     */
81 48
    public function removeIfExpired()
82
    {
83 48
        if ($this->getIsExpired() && !$this->getIsNewRecord()) {
0 ignored issues
show
Bug introduced by
It seems like getIsNewRecord() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
84
            if ($this->expiredRemovingCallback instanceof Closure && is_callable($this->expiredRemovingCallback)) {
85
                $result = call_user_func($this->expiredRemovingCallback, $this);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
86
            }
87
            $result = $this->delete();
0 ignored issues
show
Bug introduced by
It seems like delete() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
88
            $this->trigger(static::$eventExpiredRemoved, new \yii\base\ModelEvent(['data' => ['result' => $result]]));
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
89
        }
90 48
        return false;
91
    }
92
93 48
    public function onRemoveExpired($event)
94
    {
95 48
        $sender = $event->sender;
96 48
        return $sender->removeIfExpired();
97
    }
98
99
    /**
100
     * Get the current date & time in format of "Y-m-d H:i:s" or timestamp.
101
     * You can override this method to customize the return value.
102
     * @param \yii\base\ModelEvent $event
103
     * @return string Date & Time.
104
     * @since 1.1
105
     */
106 46
    public static function getCurrentDatetime($event)
107
    {
108 46
        $sender = $event->sender;
109 46
        return $sender->currentDatetime();
110
    }
111
112 46
    public function currentDatetime()
113
    {
114 46
        if ($this->timeFormat === self::$timeFormatDatetime) {
115 46
            return date('Y-m-d H:i:s');
116
        }
117
        if ($this->timeFormat === self::$timeFormatTimestamp) {
118
            return time();
119
        }
120
    }
121
122 2
    public function offsetDatetime($time = null, $offset = 0)
123
    {
124 2
        if ($this->timeFormat === self::$timeFormatDatetime) {
125 2
            return date('Y-m-d H:i:s', strtotime(((int) $offset >= 0 ? "+$offset" : "-" . abs($offset)) . " seconds", is_string($time) ? strtotime($time) : time()));
126
        }
127
        if ($this->timeFormat === self::$timeFormatTimestamp) {
128
            return (is_int($time) ? $time : time()) + $offset;
129
        }
130
    }
131
132
    /**
133
     * Get init date & time in format of "Y-m-d H:i:s" or timestamp.s
134
     * @param \yii\base\ModelEvent $event
135
     * @return string|int
136
     */
137 8
    public static function getInitDatetime($event)
138
    {
139 8
        $sender = $event->sender;
140 8
        return $sender->initDatetime();
141
    }
142
143 8
    public function initDatetime()
144
    {
145 8
        if ($this->timeFormat === self::$timeFormatDatetime) {
146 8
            return static::$initDatetime;
147
        }
148
        if ($this->timeFormat === self::$timeFormatTimestamp) {
149
            return static::$initTimestamp;
150
        }
151
        return null;
152
    }
153
154
    /**
155
     * Check whether the attribute is init datetime.
156
     * @param mixed $attribute
157
     * @return boolean
158
     */
159 4
    protected function isInitDatetime($attribute)
160
    {
161 4
        if ($this->timeFormat === self::$timeFormatDatetime) {
162 4
            return $attribute == static::$initDatetime || $attribute == null;
163
        }
164
        if ($this->timeFormat === self::$timeFormatTimestamp) {
165
            return $attribute == static::$initTimestamp || $attribute == null;
166
        }
167
        return false;
168
    }
169
170
    /**
171
     * Get the current date & time in format of "Y-m-d H:i:s".
172
     * This method is ONLY used for being triggered by event. DO NOT call,
173
     * override or modify it directly, unless you know the consequences.
174
     * @param \yii\base\Event $event
175
     * @return string Date & Time.
176
     * @since 1.1
177
     */
178 46
    public function onUpdateCurrentDatetime($event)
179
    {
180 46
        return self::getCurrentDatetime($event);
0 ignored issues
show
Compatibility introduced by
$event of type object<yii\base\Event> is not a sub-type of object<yii\base\ModelEvent>. It seems like you assume a child class of the class yii\base\Event to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
181
    }
182
183
    /**
184
     * Behaviors associated with timestamp.
185
     * @return array behaviors
186
     */
187 12
    public function getTimestampBehaviors()
188
    {
189
        return [
190
            [
191 12
                'class' => TimestampBehavior::className(),
192 12
                'createdAtAttribute' => $this->createdAtAttribute,
193 12
                'updatedAtAttribute' => $this->updatedAtAttribute,
194 12
                'value' => [$this, 'onUpdateCurrentDatetime'],
195
            ]
196 12
        ];
197
    }
198
199
    /**
200
     * Get createdAt.
201
     * @return string timestamp
202
     */
203 48
    public function getCreatedAt()
204
    {
205 48
        $createdAtAttribute = $this->createdAtAttribute;
206 48
        if (!is_string($createdAtAttribute)) {
207
            return null;
208
        }
209 48
        return $this->$createdAtAttribute;
210
    }
211
212
    /**
213
     * Get rules associated with createdAtAttribute.
214
     * @return array rules
215
     */
216 12
    public function getCreatedAtRules()
217
    {
218 12
        if (!$this->createdAtAttribute) {
219
            return [];
220
        }
221
        return [
222 12
            [[$this->createdAtAttribute], 'safe'],
223 12
        ];
224
    }
225
226
    /**
227
     * Get updatedAt.
228
     * @return string timestamp
229
     */
230
    public function getUpdatedAt()
231
    {
232
        $updatedAtAttribute = $this->updatedAtAttribute;
233
        if (!is_string($updatedAtAttribute)) {
234
            return null;
235
        }
236
        return $this->$updatedAtAttribute;
237
    }
238
239
    /**
240
     * Get rules associated with updatedAtAttribute.
241
     * @return array rules
242
     */
243 12
    public function getUpdatedAtRules()
244
    {
245 12
        if (!$this->updatedAtAttribute) {
246 1
            return [];
247
        }
248
        return [
249 11
            [[$this->updatedAtAttribute], 'safe'],
250 11
        ];
251
    }
252
}
253