Passed
Push — master ( 6b49ff...b93f48 )
by Paweł
05:24
created

MediaUpdater   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 10
c 0
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 5 2
A saveModel() 0 7 2
A details() 0 13 1
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 12.06.2018
6
 */
7
8
namespace app\components;
9
10
11
use app\components\instagram\models\Post;
12
use app\models\AccountStats;
13
use app\models\Media;
14
use yii\base\Component;
15
use yii\base\InvalidConfigException;
16
use yii\db\ActiveRecord;
17
use yii\web\ServerErrorHttpException;
18
19
class MediaUpdater extends Component
20
{
21
    /**
22
     * @var \app\models\Media
23
     */
24
    public $media;
25
26
    public function init()
27
    {
28
        parent::init();
29
        if (!$this->media instanceof Media) {
0 ignored issues
show
introduced by
$this->media is always a sub-type of app\models\Media. If $this->media can have other possible types, add them to components/MediaUpdater.php:22.
Loading history...
30
            throw new InvalidConfigException('Property \'media\' must be set and by type od \'\app\models\Media\'');
31
        }
32
    }
33
34
    public function details(Post $post): Media
35
    {
36
        $this->media->instagram_id = $post->id;
37
        $this->media->shortcode = $post->shortcode;
38
        $this->media->is_video = $post->isVideo;
39
        $this->media->caption = $post->caption;
40
        $this->media->taken_at = (new \DateTime('@' . $post->takenAt))->format('Y-m-d H:i:s');
41
        $this->media->likes = $post->likes;
42
        $this->media->comments = $post->comments;
43
44
        $this->saveModel($this->media);
45
46
        return $this->media;
47
    }
48
49
    private function saveModel(ActiveRecord $model)
50
    {
51
        if (!$model->save()) {
52
            throw new ServerErrorHttpException(sprintf('Validation: %s', json_encode($model->errors)));
53
        }
54
55
        return true;
56
    }
57
}