Passed
Branch master (d10f8f)
by Anton
10:47
created

ActiveRecordChannel::send()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 24
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
/**
3
 * @copyright Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\notifications\channels;
7
8
9
use tuyakhov\notifications\messages\DatabaseMessage;
10
use tuyakhov\notifications\NotifiableInterface;
11
use tuyakhov\notifications\NotificationInterface;
12
use yii\base\Component;
13
use yii\base\InvalidConfigException;
14
use yii\db\BaseActiveRecord;
15
16
class ActiveRecordChannel extends Component implements ChannelInterface
17
{
18
    /**
19
     * @var BaseActiveRecord|string
20
     */
21
    public $model = 'tuyakhov\notifications\models\Notification';
22
23
    public function send(NotifiableInterface $recipient, NotificationInterface $notification)
24
    {
25
        $model = \Yii::createObject($this->model);
0 ignored issues
show
Bug introduced by
It seems like $this->model can also be of type yii\db\BaseActiveRecord; however, parameter $type of yii\BaseYii::createObject() does only seem to accept array|callable|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

25
        $model = \Yii::createObject(/** @scrutinizer ignore-type */ $this->model);
Loading history...
26
27
        if (!$model instanceof BaseActiveRecord) {
28
            throw new InvalidConfigException('Model class must extend from \\yii\\db\\BaseActiveRecord');
29
        }
30
31
        /** @var DatabaseMessage $message */
32
        $message = $notification->exportFor('database');
33
        list($notifiableType, $notifiableId) = $recipient->routeNotificationFor('database');
34
        $data = [
35
            'level' => $message->level,
36
            'subject' => $message->subject,
37
            'body' => $message->body,
38
            'notifiable_type' => $notifiableType,
39
            'notifiable_id' => $notifiableId,
40
        ];
41
42
        if ($model->load($data, '')) {
43
            return $model->insert();
44
        }
45
46
        return false;
47
    }
48
}