Records::convertResponseToRecords()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 3
rs 10
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
     */
23
    private $client;
24
25 1
    public function __construct(Client $client)
26
    {
27 1
        $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
     * @param array|null $fields
39
     * @return array
40
     */
41 3
    public function get($appId, $query = '', $guestSpaceId = null, $totalCount = true, array $fields = null): array
42
    {
43 3
        $options = ['json' => ['app' => $appId, 'query' => $query]];
44 3
        if ($totalCount) {
45 3
            $options['json']['totalCount'] = $totalCount;
46
        }
47 3
        if ($fields) {
48 2
            $options['json']['fields'] = $fields;
49
        }
50
        /** @var JsonStream $stream */
51 3
        $stream = $this->client
52 3
            ->get(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
53 3
            ->getBody();
54
55 3
        return $stream->jsonSerialize();
56
    }
57
58
    /**
59
     * Get all records
60
     *
61
     * @param integer $appId
62
     * @param string $query
63
     * @param integer $guestSpaceId
64
     * @param array|null $fields
65
     * @return array
66
     */
67 1
    public function all($appId, $query = '', $guestSpaceId = null, array $fields = null): array
68
    {
69 1
        $result = [];
70 1
        $result[0] = $this->get($appId, $query . ' limit ' . self::MAX_GET_RECORDS, $guestSpaceId, true, $fields);
71 1
        $totalCount = $result[0]['totalCount'];
72 1
        if ($totalCount <= self::MAX_GET_RECORDS) {
73 1
            return $result[0]['records'];
74
        }
75
76 1
        $concurrency = $this->client->getConfig('concurrency');
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\Client::getConfig() has been deprecated: Client::getConfig will be removed in guzzlehttp/guzzle:8.0. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

76
        $concurrency = /** @scrutinizer ignore-deprecated */ $this->client->getConfig('concurrency');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
77 1
        $requests = $this->createGetRequestsCallback($appId, $query, $guestSpaceId, $fields, $totalCount);
78 1
        $pool = new Pool($this->client, $requests(), [
79 1
            'concurrency' => $concurrency ?: 1,
80 1
            'fulfilled' => static function (ResponseInterface $response, $index) use (&$result) {
81
                /** @var JsonStream $stream */
82 1
                $stream = $response->getBody();
83 1
                $result[$index+1] = array_merge($stream->jsonSerialize());
84 1
            }
85 1
        ]);
86 1
        $pool->promise()->wait();
87
88 1
        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');
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\Client::getConfig() has been deprecated: Client::getConfig will be removed in guzzlehttp/guzzle:8.0. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

101
        $headers = /** @scrutinizer ignore-deprecated */ $this->client->getConfig('headers');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
102 1
        $headers['Content-Type'] = 'application/json';
103 1
        return static function () use ($appId, $query, $guestSpaceId, $fields, $totalCount, $headers) {
104 1
            $num = ceil($totalCount / self::MAX_GET_RECORDS);
105 1
            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 1
                ];
110 1
                if ($fields) {
111 1
                    $body['fields'] = $fields;
112
                }
113 1
                yield new Request(
114 1
                    'GET',
115 1
                    KintoneApi::generateUrl('records.json', $guestSpaceId),
116 1
                    $headers,
117 1
                    \GuzzleHttp\json_encode($body)
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\json_encode() has been deprecated: json_encode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonEncode instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

117
                    /** @scrutinizer ignore-deprecated */ \GuzzleHttp\json_encode($body)

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
118 1
                );
119
            }
120 1
        };
121
    }
122
123
    /**
124
     * @param array $result
125
     * @return array
126
     */
127 1
    private function convertResponseToRecords(array  $result): array
128
    {
129 1
        ksort($result);
130 1
        $allRecords = [];
131 1
        foreach ($result as $r) {
132
            /** @var array $records */
133 1
            $records = $r['records'];
134 1
            foreach ($records as $record) {
135 1
                $allRecords[] = $record;
136
            }
137
        }
138
139 1
        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 3
    public function post($appId, array $records, $guestSpaceId = null): array
152
    {
153 3
        $options = ['json' => ['app' => $appId, 'records' => $records]];
154
155
        /** @var JsonStream $stream */
156 3
        $stream = $this->client
157 3
            ->post(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
158 3
            ->getBody();
159
160 3
        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 1
    public function put($appId, array $records, $guestSpaceId = null): array
173
    {
174 1
        $options = ['json' => ['app' => $appId, 'records' => $records]];
175
176
        /** @var JsonStream $stream */
177 1
        $stream = $this->client
178 1
            ->put(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
179 1
            ->getBody();
180
181 1
        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 1
    public function delete($appId, array $ids, $guestSpaceId = null, array $revisions = []): array
195
    {
196 1
        $options = ['json' => ['app' => $appId, 'ids' => $ids]];
197 1
        if (count($revisions) && count($ids) === count($revisions)) {
198 1
            $options['json']['revisions'] = $revisions;
199
        }
200
201
        /** @var JsonStream $stream */
202 1
        $stream = $this->client
203 1
            ->delete(KintoneApi::generateUrl('records.json', $guestSpaceId), $options)
204 1
            ->getBody();
205
206 1
        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 1
    public function putStatus($appId, array $records, $guestSpaceId = null): array
219
    {
220 1
        $options = ['json' => ['app' => $appId, 'records' => $records]];
221
222
        /** @var JsonStream $stream */
223 1
        $stream = $this->client
224 1
            ->put(KintoneApi::generateUrl('records/status.json', $guestSpaceId), $options)
225 1
            ->getBody();
226
227 1
        return $stream->jsonSerialize();
228
    }
229
}
230