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

ArticleBehavior   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 36
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A events() 0 6 1
A saveMeta() 0 14 3
A afterDelete() 0 8 3
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