Completed
Push — 0.1 ( 1296ef...144915 )
by Yuichi
19:51 queued 09:46
created

File::multiPost()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 0
cts 0
cp 0
rs 9.488
c 0
b 0
f 0
cc 3
nc 1
nop 2
crap 12
1
<?php
2
3
namespace CybozuHttp\Api\Kintone;
4
5
use CybozuHttp\Client;
6
use CybozuHttp\Api\KintoneApi;
7
use CybozuHttp\Middleware\JsonStream;
8
use GuzzleHttp\Pool;
9
use GuzzleHttp\Psr7\MultipartStream;
10
use GuzzleHttp\Psr7\Request;
11
use Psr\Http\Message\ResponseInterface;
12
13
14
/**
15
 * @author ochi51 <[email protected]>
16
 */
17
class File
18
{
19 2
    /**
20
     * @var Client
21 2
     */
22 2
    private $client;
23
24
    public function __construct(Client $client)
25
    {
26
        $this->client = $client;
27
    }
28
29
    /**
30
     * Get file
31
     * https://cybozudev.zendesk.com/hc/ja/articles/202166180#step1
32 1
     *
33
     * @param string $fileKey
34 1
     * @param int $guestSpaceId
35 1
     * @return string
36
     */
37 1
    public function get($fileKey, $guestSpaceId = null): string
38
    {
39
        $options = ['json' => ['fileKey' => $fileKey]];
40
        $response = $this->client->get(KintoneApi::generateUrl('file.json', $guestSpaceId), $options);
41
42
        return (string)$response->getBody();
43
    }
44
45
    /**
46
     * Get file stream response
47
     * https://cybozudev.zendesk.com/hc/ja/articles/202166180#step1
48 1
     *
49
     * @param string $fileKey
50
     * @param int $guestSpaceId
51 1
     * @return ResponseInterface
52 1
     */
53 1
    public function getStreamResponse($fileKey, $guestSpaceId = null): ResponseInterface
54 1
    {
55 1
        $options = [
56
            'json' => ['fileKey' => $fileKey],
57
            'stream' => true
58
        ];
59
        $response = $this->client->get(KintoneApi::generateUrl('file.json', $guestSpaceId), $options);
60
61
        return $response;
62
    }
63
64
    /**
65
     * @param array $fileKeys
66
     * @param int|null $guestSpaceId
67
     * @return array [contents, contents, ...] The order of $fileKeys
68
     */
69
    public function multiGet(array $fileKeys, $guestSpaceId = null): array
70
    {
71
        $result = [];
72
        $concurrency = $this->client->getConfig('concurrency');
73
        $headers = $this->client->getConfig('headers');
74
        $headers['Content-Type'] = 'application/json';
75
        $url = KintoneApi::generateUrl('file.json', $guestSpaceId);
76
        $requests = function () use ($fileKeys, $url, $headers) {
77
            foreach ($fileKeys as $fileKey) {
78
                $body = \GuzzleHttp\json_encode(['fileKey' => $fileKey]);
79
                yield new Request('GET', $url, $headers, $body);
80
            }
81
        };
82
        $pool = new Pool($this->client, $requests(), [
83
            'concurrency' => $concurrency ?: 1,
84
            'fulfilled' => function (ResponseInterface $response, $index) use (&$result) {
85
                $result[$index] = (string)$response->getBody();
86
            }
87
        ]);
88
        $pool->promise()->wait();
89
90
        return $result;
91
    }
92
93
    /**
94
     * Post file
95
     * https://cybozudev.zendesk.com/hc/ja/articles/201941824#step1
96
     *
97
     * @param string $path
98
     * @param int|null $guestSpaceId
99
     * @param string|null $filename
100
     * @return string
101
     */
102
    public function post($path, $guestSpaceId = null, $filename = null): string
103
    {
104
        $options = ['multipart' => [self::createMultipart($path, $filename)]];
105
        $this->changeLocale();
106
107
        /** @var JsonStream $stream */
108
        $stream = $this->client
109
            ->post(KintoneApi::generateUrl('file.json', $guestSpaceId), $options)
110
            ->getBody();
111
112
        return $stream->jsonSerialize()['fileKey'];
113
    }
114
115
    /**
116
     * @param array $fileNames
117
     * @param int|null $guestSpaceId
118
     * @return array [fileKey, fileKey, ...] The order of $fileNames
119
     * @throws \InvalidArgumentException
120
     */
121
    public function multiPost(array $fileNames, $guestSpaceId = null): array
122
    {
123
        $this->changeLocale();
124
125
        $result = [];
126
        $concurrency = $this->client->getConfig('concurrency');
127
        $headers = $this->client->getConfig('headers');
128
        $url = KintoneApi::generateUrl('file.json', $guestSpaceId);
129
        $requests = function () use ($fileNames, $url, $headers) {
130
            foreach ($fileNames as $filename) {
131
                $body = new MultipartStream([self::createMultipart($filename)]);
132
                yield new Request('POST', $url, $headers, $body);
133
            }
134
        };
135
        $pool = new Pool($this->client, $requests(), [
136
            'concurrency' => $concurrency ?: 1,
137
            'fulfilled' => function (ResponseInterface $response, $index) use (&$result) {
138
                /** @var JsonStream $stream */
139
                $stream = $response->getBody();
140
                $result[$index] = $stream->jsonSerialize()['fileKey'];
141
            }
142
        ]);
143
        $pool->promise()->wait();
144
        ksort($result);
145
146
        return $result;
147
    }
148
149
    /**
150
     * Returns locale independent base name of the given path.
151
     *
152
     * @param string $name The new file name
153
     * @return string containing
154
     */
155
    public static function getFilename($name): string
156
    {
157
        $originalName = str_replace('\\', '/', $name);
158
        $pos = strrpos($originalName, '/');
159
        $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1);
160
161
        return $originalName;
162
    }
163
164
    private function changeLocale(): void
165
    {
166
        $baseUri = $this->client->getConfig('base_uri');
167
        if (strpos($baseUri->getHost(), 'cybozu.com') > 0) { // Japanese kintone
168
            setlocale(LC_ALL, 'ja_JP.UTF-8');
169
        }
170
    }
171
172
    /**
173
     * @param string $path
174
     * @param string|null $filename
175
     * @return array
176
     */
177
    private static function createMultipart($path, $filename = null): array
178
    {
179
        return [
180
            'name' => 'file',
181
            'filename' => self::getFilename($filename ?: $path),
182
            'contents' => fopen($path, 'rb'),
183
            'headers' => ['Content-Type' => mime_content_type($path)]
184
        ];
185
    }
186
}
187