ReadableBehavior   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
eloc 12
c 2
b 0
f 0
dl 0
loc 53
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isUnread() 0 3 1
A isRead() 0 3 1
A markAsRead() 0 7 2
A markAsUnread() 0 7 2
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->{$this->readAttribute} = date('Y-m-d H:i:s');
28
            $model->update(false, [$this->readAttribute]);
29
        }
30
    }
31
32
    /**
33
     * Mark the notification as unread.
34
     * @return void
35
     * @throws \Exception
36
     * @throws \Throwable
37
     */
38
    public function markAsUnread()
39
    {
40
        /** @var ActiveRecordInterface $model */
41
        $model = $this->owner;
42
        if (!is_null($model->{$this->readAttribute})) {
43
            $model->{$this->readAttribute} = null;
44
            $model->update(false, [$this->readAttribute]);
45
        }
46
    }
47
48
    /**
49
     * Determine if a notification has been read.
50
     *
51
     * @return bool
52
     */
53
    public function isRead()
54
    {
55
        return $this->owner->{$this->readAttribute} !== null;
56
    }
57
    /**
58
     * Determine if a notification has not been read.
59
     *
60
     * @return bool
61
     */
62
    public function isUnread()
63
    {
64
        return $this->owner->{$this->readAttribute} === null;
65
    }
66
}
67