Passed
Pull Request — master (#50)
by Paweł
02:57
created

MediaManager::updateUsernames()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 18
nc 2
nop 2
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 12.01.2018
6
 */
7
8
namespace app\components;
9
10
11
use app\components\instagram\AccountScraper;
12
use app\models\Account;
13
use app\models\Media;
14
use app\models\MediaAccount;
15
use app\models\MediaStats;
16
use app\models\MediaTag;
17
use app\models\Tag;
18
use jakim\ig\Text;
19
use Jakim\Model\Post;
20
use yii\base\Component;
21
use yii\base\Exception;
22
23
class MediaManager extends Component
24
{
25
    /**
26
     * @var \app\models\Account
27
     */
28
    public $account;
29
30
    /**
31
     * @param \app\models\Media $media
32
     * @param \Jakim\Model\Post $data
33
     * @throws \yii\base\Exception
34
     * @throws \yii\base\InvalidConfigException
35
     * @throws \yii\db\Exception
36
     */
37
    public function update(Media $media, Post $data)
38
    {
39
        $media = $this->updateDetails($media, $data);
40
41
        if (!$this->account) {
42
            $this->account = $media->account;
43
            $this->account->refresh();
44
        }
45
46
        if ($media->caption) {
47
            $tags = (array)Text::getTags($media->caption);
48
            $this->updateTags($media, $tags);
49
50
            $usernames = (array)Text::getUsernames($media->caption);
51
            // ignore owner of media
52
            ArrayHelper::removeValue($usernames, $this->account->username);
53
            $this->updateUsernames($media, $usernames);
54
        }
55
56
        $this->updateStats($media, $data);
57
    }
58
59
    /**
60
     * @param \app\models\Media $media
61
     * @param \Jakim\Model\Post $data
62
     * @return \app\models\Media
63
     * @throws \yii\base\Exception
64
     */
65
    public function updateDetails(Media $media, Post $data): Media
66
    {
67
        $media->instagram_id = $data->id;
68
        $media->shortcode = $data->shortcode;
69
        $media->is_video = $data->isVideo;
70
        $media->caption = $data->caption;
71
        $media->taken_at = (new \DateTime('@' . $data->takenAt))->format('Y-m-d H:i:s');
72
73
        if (!$media->account_id && $this->account) {
74
            $media->account_id = $this->account->id;
75
        }
76
77
        if (!$media->save()) {
78
            throw new Exception(json_encode($media->errors));
79
        }
80
81
        return $media;
82
    }
83
84
    /**
85
     * @param \app\models\Media $media
86
     * @param \Jakim\Model\Post $data
87
     * @return \app\models\MediaStats|null
88
     */
89
    public function updateStats(Media $media, Post $data): ?MediaStats
90
    {
91
        $account = $media->account ?? $this->account;
92
        if (empty($account->lastAccountStats)) {
93
            return null;
94
        }
95
        $mediaStats = null;
96
        if ($this->statsNeedUpdate($media, $data)) {
0 ignored issues
show
Bug introduced by
The method statsNeedUpdate() does not exist on app\components\MediaManager. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

96
        if ($this->/** @scrutinizer ignore-call */ statsNeedUpdate($media, $data)) {
Loading history...
97
            $mediaStats = new MediaStats();
98
            $mediaStats->likes = $data->likes;
99
            $mediaStats->comments = $data->comments;
100
            $mediaStats->account_followed_by = $this->account->lastAccountStats->followed_by;
101
            $mediaStats->account_follows = $this->account->lastAccountStats->follows;
102
            $media->link('mediaStats', $mediaStats);
103
        }
104
105
        return $mediaStats;
106
    }
107
108
    public function updateUsernames(Media $media, array $usernames)
109
    {
110
        $manager = \Yii::createObject(AccountManager::class);
111
        $manager->saveUsernames($usernames);
112
        if ($this->account) {
113
            $manager->monitorMultiple($usernames, $this->account);
114
        }
115
116
        $createdAt = (new \DateTime())->format('Y-m-d H:i:s');
117
        $rows = array_map(function ($id) use ($media, $createdAt) {
118
            return [
119
                $media->id,
120
                $id,
121
                $createdAt,
122
            ];
123
        }, Account::find()
124
            ->andWhere(['username' => $usernames])
125
            ->column());
126
127
        $sql = \Yii::$app->db->queryBuilder
128
            ->batchInsert(MediaAccount::tableName(), ['media_id', 'account_id', 'created_at'], $rows);
129
        $sql = str_replace('INSERT INTO ', 'INSERT IGNORE INTO ', $sql);
130
        \Yii::$app->db->createCommand($sql)
131
            ->execute();
132
    }
133
134
    /**
135
     * @param \app\models\Media $media
136
     * @param array $tags
137
     * @throws \yii\base\InvalidConfigException
138
     * @throws \yii\db\Exception
139
     */
140
    public function updateTags(Media $media, array $tags)
141
    {
142
        $manager = \Yii::createObject(TagManager::class);
143
        $manager->saveTags($tags);
144
145
        $createdAt = (new \DateTime())->format('Y-m-d H:i:s');
146
        $rows = array_map(function ($id) use ($media, $createdAt) {
147
            return [
148
                $media->id,
149
                $id,
150
                $createdAt,
151
            ];
152
        }, Tag::find()
153
            ->andWhere(['name' => $tags])
154
            ->column());
155
156
        $sql = \Yii::$app->db->queryBuilder
157
            ->batchInsert(MediaTag::tableName(), ['media_id', 'tag_id', 'created_at'], $rows);
158
        $sql = str_replace('INSERT INTO ', 'INSERT IGNORE INTO ', $sql);
159
        \Yii::$app->db->createCommand($sql)
160
            ->execute();
161
    }
162
}