Passed
Branch master (3eb6ea)
by Anton
06:04
created

ReadableBehavior::isUnread()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * @copyright Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\notifications\behaviors;
7
8
9
use yii\base\Behavior;
10
use yii\db\ActiveRecordInterface;
11
12
class ReadableBehavior extends Behavior
13
{
14
15
    public $readAttribute = 'read_at';
16
17
    /**
18
     * Mark the notification as read.
19
     * @throws \Exception
20
     * @throws \Throwable
21
     */
22
    public function markAsRead()
23
    {
24
        /** @var ActiveRecordInterface $model */
25
        $model = $this->owner;
26
        if (is_null($model->{$this->readAttribute})) {
27
            $model->update(false, [$this->readAttribute => date('Y-m-d H:i:s')]);
28
        }
29
    }
30
31
    /**
32
     * Mark the notification as unread.
33
     * @return void
34
     * @throws \Exception
35
     * @throws \Throwable
36
     */
37
    public function markAsUnread()
38
    {
39
        /** @var ActiveRecordInterface $model */
40
        $model = $this->owner;
41
        if (!is_null($model->{$this->readAttribute})) {
42
            $model->update(false, [$this->readAttribute => null]);
43
        }
44
    }
45
46
    /**
47
     * Determine if a notification has been read.
48
     *
49
     * @return bool
50
     */
51
    public function isRead()
52
    {
53
        return $this->owner->{$this->readAttribute} !== null;
54
    }
55
    /**
56
     * Determine if a notification has not been read.
57
     *
58
     * @return bool
59
     */
60
    public function isUnread()
61
    {
62
        return $this->owner->{$this->readAttribute} === null;
63
    }
64
}