Completed
Pull Request — master (#308)
by Carlos
05:21 queued 02:19
created

Material::stats()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
/**
13
 * Material.php.
14
 *
15
 * @author    overtrue <[email protected]>
16
 * @copyright 2015 overtrue <[email protected]>
17
 *
18
 * @link      https://github.com/overtrue
19
 * @link      http://overtrue.me
20
 */
21
namespace EasyWeChat\Material;
22
23
use EasyWeChat\Core\AbstractAPI;
24
use EasyWeChat\Core\Exceptions\InvalidArgumentException;
25
use EasyWeChat\Message\Article;
26
27
/**
28
 * Class Material.
29
 */
30
class Material extends AbstractAPI
31
{
32
    /**
33
     * Allow media type.
34
     *
35
     * @var array
36
     */
37
    protected $allowTypes = ['image', 'voice', 'video', 'thumb', 'news_image'];
38
39
    const API_GET = 'https://api.weixin.qq.com/cgi-bin/material/get_material';
40
    const API_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/material/add_material';
41
    const API_DELETE = 'https://api.weixin.qq.com/cgi-bin/material/del_material';
42
    const API_STATS = 'https://api.weixin.qq.com/cgi-bin/material/get_materialcount';
43
    const API_LISTS = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material';
44
    const API_NEWS_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/material/add_news';
45
    const API_NEWS_UPDATE = 'https://api.weixin.qq.com/cgi-bin/material/update_news';
46
    const API_NEWS_IMAGE_UPLOAD = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg';
47
48
    /**
49
     * Upload image.
50
     *
51
     * @param string $path
52
     *
53
     * @return string
54
     */
55 1
    public function uploadImage($path)
56
    {
57 1
        return $this->uploadMedia('image', $path);
58
    }
59
60
    /**
61
     * Upload voice.
62
     *
63
     * @param string $path
64
     *
65
     * @return string
66
     */
67 1
    public function uploadVoice($path)
68
    {
69 1
        return $this->uploadMedia('voice', $path);
70
    }
71
72
    /**
73
     * Upload thumb.
74
     *
75
     * @param string $path
76
     *
77
     * @return string
78
     */
79 1
    public function uploadThumb($path)
80
    {
81 1
        return $this->uploadMedia('thumb', $path);
82
    }
83
84
    /**
85
     * Upload video.
86
     *
87
     * @param string $path
88
     * @param string $title
89
     * @param string $description
90
     *
91
     * @return string
92
     */
93 1
    public function uploadVideo($path, $title, $description)
94
    {
95
        $params = [
96 1
            'description' => json_encode(
97
                [
98 1
                    'title' => $title,
99 1
                    'introduction' => $description,
100 1
                ], JSON_UNESCAPED_UNICODE),
101 1
        ];
102
103 1
        return $this->uploadMedia('video', $path, $params);
104
    }
105
106
    /**
107
     * Upload articles.
108
     *
109
     * @param array|Article $articles
110
     *
111
     * @return string
112
     */
113 1
    public function uploadArticle($articles)
114
    {
115 1
        if (!empty($articles['title']) || $articles instanceof Article) {
116 1
            $articles = [$articles];
117 1
        }
118
119 1
        $params = ['articles' => array_map(function ($article) {
120 1
            if ($article instanceof Article) {
121 1
                return $article->only([
122 1
                    'title', 'thumb_media_id', 'author', 'digest',
123 1
                    'show_cover_pic', 'content', 'content_source_url',
124 1
                    ]);
125
            }
126
127 1
            return $article;
128 1
        }, $articles)];
129
130 1
        return $this->parseJSON('json', [self::API_NEWS_UPLOAD, $params]);
131
    }
132
133
    /**
134
     * Update article.
135
     *
136
     * @param string $mediaId
137
     * @param array  $article
138
     * @param int    $index
139
     *
140
     * @return bool
141
     */
142 1
    public function updateArticle($mediaId, $article, $index = 0)
143
    {
144
        $params = [
145 1
            'media_id' => $mediaId,
146 1
            'index' => $index,
147 1
            'articles' => isset($article['title']) ? $article : (isset($article[$index]) ? $article[$index] : []),
148 1
        ];
149
150 1
        return $this->parseJSON('json', [self::API_NEWS_UPDATE, $params]);
151
    }
152
153
    /**
154
     * Upload image for article.
155
     *
156
     * @param string $path
157
     *
158
     * @return string
159
     */
160 1
    public function uploadArticleImage($path)
161
    {
162 1
        return $this->uploadMedia('news_image', $path);
163
    }
164
165
    /**
166
     * Fetch material.
167
     *
168
     * @param string $mediaId
169
     *
170
     * @return mixed
171
     */
172 1
    public function get($mediaId)
173
    {
174 1
        $response = $this->getHttp()->json(self::API_GET, ['media_id' => $mediaId]);
175
176 1
        foreach ($response->getHeader('Content-Type') as $mime) {
177 1
            if (preg_match('/(image|video|audio)/i', $mime)) {
178 1
                return $response->getBody();
179
            }
180 1
        }
181
182 1
        $json = $this->getHttp()->parseJSON($response);
183
184
        // XXX: 微信开发这帮混蛋,尼玛文件二进制输出不带header,简直日了!!!
185 1
        if (!$json) {
186
            return $response->getBody();
187
        }
188
189 1
        $this->checkAndThrow($json);
190
191 1
        return $json;
192
    }
193
194
    /**
195
     * Delete material by media ID.
196
     *
197
     * @param string $mediaId
198
     *
199
     * @return bool
200
     */
201 1
    public function delete($mediaId)
202
    {
203 1
        return $this->parseJSON('json', [self::API_DELETE, ['media_id' => $mediaId]]);
204
    }
205
206
    /**
207
     * List materials.
208
     *
209
     * example:
210
     *
211
     * {
212
     *   "total_count": TOTAL_COUNT,
213
     *   "item_count": ITEM_COUNT,
214
     *   "item": [{
215
     *             "media_id": MEDIA_ID,
216
     *             "name": NAME,
217
     *             "update_time": UPDATE_TIME
218
     *         },
219
     *         // more...
220
     *   ]
221
     * }
222
     *
223
     * @param string $type
224
     * @param int    $offset
225
     * @param int    $count
226
     *
227
     * @return array
228
     */
229 1
    public function lists($type, $offset = 0, $count = 20)
230
    {
231
        $params = [
232 1
            'type' => $type,
233 1
            'offset' => intval($offset),
234 1
            'count' => min(20, $count),
235 1
        ];
236
237 1
        return $this->parseJSON('json', [self::API_LISTS, $params]);
238
    }
239
240
    /**
241
     * Get stats of materials.
242
     *
243
     * @return array
244
     */
245 1
    public function stats()
246
    {
247 1
        return $this->parseJSON('get', [self::API_STATS]);
248
    }
249
250
    /**
251
     * Upload material.
252
     *
253
     * @param string $type
254
     * @param string $path
255
     * @param array  $form
256
     *
257
     * @return string
258
     *
259
     * @throws InvalidArgumentException
260
     */
261 5
    protected function uploadMedia($type, $path, array $form = [])
262
    {
263 5
        if (!file_exists($path) || !is_readable($path)) {
264 1
            throw new InvalidArgumentException("File does not exist, or the file is unreadable: '$path'");
265
        }
266
267 5
        $form['type'] = $type;
268
269 5
        return $this->parseJSON('upload', [$this->getAPIByType($type), ['media' => $path], $form]);
270
    }
271
272
    /**
273
     * Get API by type.
274
     *
275
     * @param string $type
276
     *
277
     * @return string
278
     */
279 5
    public function getAPIByType($type)
280
    {
281
        switch ($type) {
282 5
            case 'news_image':
283 1
                $api = self::API_NEWS_IMAGE_UPLOAD;
284 1
                break;
285 4
            default:
286 4
                $api = self::API_UPLOAD;
287 4
        }
288
289 5
        return $api;
290
    }
291
}
292