Completed
Push — master ( b341d2...2686ad )
by Carlos
01:37 queued 12s
created

src/OfficialAccount/Material/Client.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
namespace EasyWeChat\OfficialAccount\Material;
13
14
use EasyWeChat\Kernel\BaseClient;
15
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
16
use EasyWeChat\Kernel\Http\StreamResponse;
17
use EasyWeChat\Kernel\Messages\Article;
18
19
/**
20
 * Class Client.
21
 *
22
 * @author overtrue <[email protected]>
23
 */
24
class Client extends BaseClient
25
{
26
    /**
27
     * Allow media type.
28
     *
29
     * @var array
30
     */
31
    protected $allowTypes = ['image', 'voice', 'video', 'thumb', 'news_image'];
32
33
    /**
34
     * Upload image.
35
     *
36
     * @param string $path
37
     *
38
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
39
     */
40
    public function uploadImage(string $path)
41
    {
42
        return $this->upload('image', $path);
43
    }
44
45
    /**
46
     * Upload voice.
47
     *
48
     * @param string $path
49
     *
50
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
51
     */
52
    public function uploadVoice(string $path)
53
    {
54
        return $this->upload('voice', $path);
55
    }
56
57
    /**
58
     * Upload thumb.
59
     *
60
     * @param string $path
61
     *
62
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
63
     */
64
    public function uploadThumb(string $path)
65
    {
66
        return $this->upload('thumb', $path);
67
    }
68
69
    /**
70
     * Upload video.
71
     *
72
     * @param string $path
73
     * @param string $title
74
     * @param string $description
75
     *
76
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
77
     */
78
    public function uploadVideo(string $path, string $title, string $description)
79
    {
80
        $params = [
81
            'description' => json_encode(
82
                [
83
                    'title' => $title,
84
                    'introduction' => $description,
85
                ], JSON_UNESCAPED_UNICODE),
86
        ];
87
88
        return $this->upload('video', $path, $params);
89
    }
90
91
    /**
92
     * Upload articles.
93
     *
94
     * @param array|Article $articles
95
     *
96
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
97
     */
98
    public function uploadArticle($articles)
99
    {
100
        if ($articles instanceof Article || !empty($articles['title'])) {
101
            $articles = [$articles];
102
        }
103
104
        $params = ['articles' => array_map(function ($article) {
105
            if ($article instanceof Article) {
106
                return $article->transformForJsonRequestWithoutType();
107
            }
108
109
            return $article;
110
        }, $articles)];
111
112
        return $this->httpPostJson('cgi-bin/material/add_news', $params);
113
    }
114
115
    /**
116
     * Update article.
117
     *
118
     * @param string        $mediaId
119
     * @param array|Article $article
120
     * @param int           $index
121
     *
122
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
123
     */
124
    public function updateArticle(string $mediaId, $article, int $index = 0)
125
    {
126
        if ($article instanceof Article) {
127
            $article = $article->transformForJsonRequestWithoutType();
128
        }
129
130
        $params = [
131
            'media_id' => $mediaId,
132
            'index' => $index,
133
            'articles' => isset($article['title']) ? $article : (isset($article[$index]) ? $article[$index] : []),
134
        ];
135
136
        return $this->httpPostJson('cgi-bin/material/update_news', $params);
137
    }
138
139
    /**
140
     * Upload image for article.
141
     *
142
     * @param string $path
143
     *
144
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
145
     */
146
    public function uploadArticleImage(string $path)
147
    {
148
        return $this->upload('news_image', $path);
149
    }
150
151
    /**
152
     * Fetch material.
153
     *
154
     * @param string $mediaId
155
     *
156
     * @return mixed
157
     */
158 View Code Duplication
    public function get(string $mediaId)
159
    {
160
        $response = $this->requestRaw('cgi-bin/material/get_material', 'POST', ['json' => ['media_id' => $mediaId]]);
161
162
        if (false === strpos($response->getHeaderLine('Content-Type'), 'text')) {
163
            return StreamResponse::buildFromPsrResponse($response);
164
        }
165
166
        return $this->resolveResponse($response, $this->app['config']->get('response_type'));
167
    }
168
169
    /**
170
     * Delete material by media ID.
171
     *
172
     * @param string $mediaId
173
     *
174
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
175
     */
176
    public function delete(string $mediaId)
177
    {
178
        return $this->httpPostJson('cgi-bin/material/del_material', ['media_id' => $mediaId]);
179
    }
180
181
    /**
182
     * List materials.
183
     *
184
     * example:
185
     *
186
     * {
187
     *   "total_count": TOTAL_COUNT,
188
     *   "item_count": ITEM_COUNT,
189
     *   "item": [{
190
     *             "media_id": MEDIA_ID,
191
     *             "name": NAME,
192
     *             "update_time": UPDATE_TIME
193
     *         },
194
     *         // more...
195
     *   ]
196
     * }
197
     *
198
     * @param string $type
199
     * @param int    $offset
200
     * @param int    $count
201
     *
202
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
203
     */
204
    public function list(string $type, int $offset = 0, int $count = 20)
205
    {
206
        $params = [
207
            'type' => $type,
208
            'offset' => intval($offset),
209
            'count' => min(20, $count),
210
        ];
211
212
        return $this->httpPostJson('cgi-bin/material/batchget_material', $params);
213
    }
214
215
    /**
216
     * Get stats of materials.
217
     *
218
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
219
     */
220
    public function stats()
221
    {
222
        return $this->httpGet('cgi-bin/material/get_materialcount');
223
    }
224
225
    /**
226
     * Upload material.
227
     *
228
     * @param string $type
229
     * @param string $path
230
     * @param array  $form
231
     *
232
     * @return \Psr\Http\Message\ResponseInterface|\EasyWeChat\Kernel\Support\Collection|array|object|string
233
     *
234
     * @throws InvalidArgumentException
235
     */
236
    public function upload(string $type, string $path, array $form = [])
237
    {
238 View Code Duplication
        if (!file_exists($path) || !is_readable($path)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
            throw new InvalidArgumentException(sprintf('File does not exist, or the file is unreadable: "%s"', $path));
240
        }
241
242
        $form['type'] = $type;
243
244
        return $this->httpUpload($this->getApiByType($type), ['media' => $path], $form);
245
    }
246
247
    /**
248
     * Get API by type.
249
     *
250
     * @param string $type
251
     *
252
     * @return string
253
     */
254
    public function getApiByType(string $type)
255
    {
256
        switch ($type) {
257
            case 'news_image':
258
                return 'cgi-bin/media/uploadimg';
259
            default:
260
                return 'cgi-bin/material/add_material';
261
        }
262
    }
263
}
264