Completed
Push — multiple-files ( 3118de )
by Yuichi
06:17
created

File::post()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

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