Completed
Push — master ( 630802...d9facf )
by Razon
02:13
created

ArticleBehavior::events()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 0
1
<?php
2
namespace App\Behavior;
3
4
use App\Factory\ArticleMetaFactory;
5
use App\Model\Article;
6
use yii\base\Behavior;
7
use yii\base\Event;
8
use yii\db\ActiveRecord;
9
10
class ArticleBehavior extends Behavior
11
{
12
    public function events()
13
    {
14
        return [
15
            ActiveRecord::EVENT_AFTER_INSERT => 'saveMeta',
16
            ActiveRecord::EVENT_AFTER_UPDATE => 'saveMeta',
17
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
18
        ];
19
    }
20
21
    public function saveMeta(Event $event)
22
    {
23
        /** @var Article $model */
24
        $model = $event->sender;
25
26
        $meta = ArticleMetaFactory::findByArticleId($model->id);
27
        if (!$meta) {
0 ignored issues
show
introduced by
$meta is of type App\Model\ArticleMeta, thus it always evaluated to true.
Loading history...
28
            $meta = ArticleMetaFactory::create($model->id, $model->content);
29
        } else {
30
            $meta->content = $model->content;
31
        }
32
        if (!$meta->save()) {
33
            Yii::error($meta->getErrors(), __METHOD__);
0 ignored issues
show
Bug introduced by
The type App\Behavior\Yii was not found. Did you mean Yii? If so, make sure to prefix the type with \.
Loading history...
34
            throw new \Exception('Unable to save article meta');
35
        }
36
    }
37
38
    public function afterDelete(Event $event)
39
    {
40
        /** @var Article $model */
41
        $model = $event->sender;
42
43
        $meta = ArticleMetaFactory::findByArticleId($model->id);
44
        if ($meta && $meta->delete() === false) {
45
           throw new \Exception('Unable to delete article meta');
46
        }
47
    }
48
}
49