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

Records::all()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 7
cts 7
cp 1
rs 9.552
c 0
b 0
f 0
cc 3
nc 2
nop 4
crap 3
1
<?php
2
3
namespace CybozuHttp\Api\Kintone;
4
5
use CybozuHttp\Middleware\JsonStream;
6
use GuzzleHttp\Pool;
7
use GuzzleHttp\Psr7\Request;
8
use Psr\Http\Message\ResponseInterface;
9
use CybozuHttp\Client;
10
use CybozuHttp\Api\KintoneApi;
11
12
/**
13
 * @author ochi51 <[email protected]>
14
 */
15
class Records
16
{
17
    public const MAX_GET_RECORDS = 500;
18
    public const MAX_POST_RECORDS = 100;
19
20
    /**
21
     * @var Client
22 2
     */
23
    private $client;
24 2
25 2
    public function __construct(Client $client)
26
    {
27
        $this->client = $client;
28
    }
29
30
    /**
31
     * Get records
32
     * https://cybozudev.zendesk.com/hc/ja/articles/202331474#step2
33
     *
34
     * @param integer $appId
35
     * @param string $query
36
     * @param integer $guestSpaceId
37
     * @param boolean $totalCount
38 2
     * @param array|null $fields
39
     * @return array
40 2
     */
41 2
    public function get($appId, $query = '', $guestSpaceId = null, $totalCount = true, array $fields = null): array
42 2
    {
43 2
        $options = ['json' => ['app' => $appId, 'query' => $query]];
44 2
        if ($totalCount) {
45 1
            $options['json']['totalCount'] = $totalCount;
46 1
        }
47
        if ($fields) {
48 2
            $options['json']['fields'] = $fields;
49 2
        }
50 2
        /** @var JsonStream $stream */
51
        $stream = $this->client
52
            ->get(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
53
            ->getBody();
54
55
        return $stream->jsonSerialize();
56
    }
57
58
    /**
59
     * Get all records
60
     *
61
     * @param integer $appId
62 1
     * @param string $query
63
     * @param integer $guestSpaceId
64 1
     * @param array|null $fields
65
     * @return array
66 1
     */
67 1
    public function all($appId, $query = '', $guestSpaceId = null, array $fields = null): array
68 1
    {
69
        $result = [];
70
        $result[0] = $this->get($appId, $query . ' limit ' . self::MAX_GET_RECORDS, $guestSpaceId, true, $fields);
71
        $totalCount = $result[0]['totalCount'];
72
        if ($totalCount <= self::MAX_GET_RECORDS) {
73
            return $result[0]['records'];
74
        }
75
76
        $concurrency = $this->client->getConfig('concurrency');
77
        $requests = $this->createGetRequestsCallback($appId, $query, $guestSpaceId, $fields, $totalCount);
78
        $pool = new Pool($this->client, $requests(), [
79
            'concurrency' => $concurrency ?: 1,
80 1
            'fulfilled' => function (ResponseInterface $response, $index) use (&$result) {
81
                /** @var JsonStream $stream */
82 1
                $stream = $response->getBody();
83
                $result[$index+1] = array_merge($stream->jsonSerialize());
84 1
            }
85 1
        ]);
86 1
        $pool->promise()->wait();
87
88
        return $this->convertResponseToRecords($result);
89
    }
90
91
    /**
92
     * @param integer $appId
93
     * @param string $query
94
     * @param integer $guestSpaceId
95
     * @param array|null $fields
96
     * @param integer $totalCount
97
     * @return \Closure
98
     */
99 1
    private function createGetRequestsCallback($appId, $query, $guestSpaceId, $fields, $totalCount): callable
100
    {
101 1
        $headers = $this->client->getConfig('headers');
102 1
        $headers['Content-Type'] = 'application/json';
103
        return function () use ($appId, $query, $guestSpaceId, $fields, $totalCount, $headers) {
104
            $num = ceil($totalCount / self::MAX_GET_RECORDS);
105
            for ($i = 1; $i < $num; $i++) {
106 1
                $body = [
107 1
                    'app' => $appId,
108 1
                    'query' => $query . ' limit ' . self::MAX_GET_RECORDS . ' offset ' . $i * self::MAX_GET_RECORDS,
109
                ];
110
                if ($fields) {
111
                    $body['fields'] = $fields;
112
                }
113
                yield new Request(
114
                    'GET',
115
                    KintoneApi::generateUrl('records.json', $guestSpaceId),
116
                    $headers,
117
                    \GuzzleHttp\json_encode($body)
118
                );
119
            }
120 3
        };
121
    }
122 1
123
    /**
124 1
     * @param array $result
125 3
     * @return array
126
     */
127
    private function convertResponseToRecords(array  $result): array
128
    {
129
        ksort($result);
130
        $allRecords = [];
131
        foreach ($result as $r) {
132
            /** @var array $records */
133
            $records = $r['records'];
134
            foreach ($records as $record) {
135
                $allRecords[] = $record;
136
            }
137
        }
138
139
        return $allRecords;
140
    }
141
142
    /**
143
     * Post records
144
     * https://cybozudev.zendesk.com/hc/ja/articles/202166160#step2
145
     *
146
     * @param integer $appId
147
     * @param array $records
148
     * @param integer $guestSpaceId
149
     * @return array
150
     */
151
    public function post($appId, array $records, $guestSpaceId = null): array
152
    {
153
        $options = ['json' => ['app' => $appId, 'records' => $records]];
154
155
        /** @var JsonStream $stream */
156
        $stream = $this->client
157
            ->post(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
158
            ->getBody();
159
160
        return $stream->jsonSerialize();
161
    }
162
163
    /**
164
     * Put records
165
     * https://cybozudev.zendesk.com/hc/ja/articles/201941784#step2
166
     *
167
     * @param integer $appId
168
     * @param array $records
169
     * @param integer $guestSpaceId
170
     * @return array
171
     */
172
    public function put($appId, array $records, $guestSpaceId = null): array
173
    {
174
        $options = ['json' => ['app' => $appId, 'records' => $records]];
175
176
        /** @var JsonStream $stream */
177
        $stream = $this->client
178
            ->put(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
179
            ->getBody();
180
181
        return $stream->jsonSerialize();
182
    }
183
184
    /**
185
     * Delete records
186
     * https://cybozudev.zendesk.com/hc/ja/articles/201941794
187
     *
188
     * @param integer $appId
189
     * @param array $ids
190
     * @param integer $guestSpaceId
191
     * @param array $revisions
192
     * @return array
193
     */
194
    public function delete($appId, array $ids, $guestSpaceId = null, array $revisions = []): array
195
    {
196
        $options = ['json' => ['app' => $appId, 'ids' => $ids]];
197
        if (count($revisions) && count($ids) === count($revisions)) {
198
            $options['json']['revisions'] = $revisions;
199
        }
200
201
        /** @var JsonStream $stream */
202
        $stream = $this->client
203
            ->delete(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
204
            ->getBody();
205
206
        return $stream->jsonSerialize();
207
    }
208
209
    /**
210
     * Put records status
211
     * https://cybozudev.zendesk.com/hc/ja/articles/204791550#anchor_changeRecordStatusBulk
212
     *
213
     * @param integer $appId
214
     * @param array $records
215
     * @param integer $guestSpaceId
216
     * @return array
217
     */
218
    public function putStatus($appId, array $records, $guestSpaceId = null): array
219
    {
220
        $options = ['json' => ['app' => $appId, 'records' => $records]];
221
222
        /** @var JsonStream $stream */
223
        $stream = $this->client
224
            ->put(KintoneApi::generateUrl('records/status.json', $guestSpaceId), $options)
225
            ->getBody();
226
227
        return $stream->jsonSerialize();
228
    }
229
}
230