GusApi::getMessage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GusApi;
6
7
use DateTimeImmutable;
8
use DateTimeZone;
9
use GusApi\Client\Builder;
10
use GusApi\Client\BuilderInterface;
11
use GusApi\Client\GusApiClient;
12
use GusApi\Exception\InvalidReportTypeException;
13
use GusApi\Exception\InvalidServerResponseException;
14
use GusApi\Exception\InvalidUserKeyException;
15
use GusApi\Exception\NotFoundException;
16
use GusApi\Type\Request\GetBulkReport;
17
use GusApi\Type\Request\GetFullReport;
18
use GusApi\Type\Request\GetValue;
19
use GusApi\Type\Request\Login;
20
use GusApi\Type\Request\Logout;
21
use GusApi\Type\Request\SearchData;
22
use GusApi\Type\Request\SearchParameters;
23
use GusApi\Type\Response\SearchResponseCompanyData;
24
25
/**
26
 * @author Janusz Żukowicz <[email protected]>
27
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
28
 */
29
class GusApi
30
{
31
    protected const MAX_IDENTIFIERS = 20;
32
33
    protected const SERVICE_TIME_ZONE = 'Europe/Warsaw';
34
35
    protected const SERVICE_STATUS_DATE_FORMAT = 'd-m-Y';
36
    protected GusApiClient $apiClient;
37
    private string $sessionId;
38
39
    public function __construct(private string $userKey, string $env = 'prod', ?BuilderInterface $builder = null)
40
    {
41
        $builder ??= new Builder($env);
42
        $this->apiClient = $builder->build();
43
    }
44
45
    public static function createWithApiClient(string $userKey, GusApiClient $apiClient): self
46
    {
47
        return new self($userKey, 'prod', new Builder('prod', $apiClient));
48
    }
49
50
    public function getSessionId(): string
51
    {
52
        $this->ensureSession();
53
54
        return $this->sessionId;
55
    }
56
57
    public function setSessionId(string $sessionId): void
58
    {
59
        $this->sessionId = $sessionId;
60
    }
61
62
    /**
63
     * @throws InvalidUserKeyException
64
     */
65
    public function login(): bool
66
    {
67
        $result = $this->apiClient->login(new Login($this->userKey));
68
69
        if (empty($result->getZalogujResult())) {
70
            throw new InvalidUserKeyException(sprintf("User key '%s' is invalid", $this->userKey));
71
        }
72
73
        $this->sessionId = $result->getZalogujResult();
74
75
        return true;
76
    }
77
78
    public function logout(): bool
79
    {
80
        return $this->apiClient->logout(new Logout($this->sessionId))->getWylogujResult();
81
    }
82
83
    public function isLogged(): bool
84
    {
85
        if (!isset($this->sessionId)) {
86
            return false;
87
        }
88
89
        return (bool) $this->getSessionStatus();
90
    }
91
92
    /**
93
     * @throws InvalidServerResponseException
94
     */
95
    public function dataStatus(): DateTimeImmutable
96
    {
97
        $this->ensureSession();
98
        $result = $this->apiClient->getValue(
99
            new GetValue(ParamName::STATUS_DATE_STATE),
100
            $this->sessionId
101
        );
102
103
        $dataStatus = DateTimeImmutable::createFromFormat(
104
            self::SERVICE_STATUS_DATE_FORMAT,
105
            $result->getGetValueResult(),
106
            new DateTimeZone(self::SERVICE_TIME_ZONE)
107
        );
108
109
        if (false === $dataStatus) {
110
            throw new InvalidServerResponseException(sprintf('Invalid response, expected date in format "%s" given %s', self::SERVICE_STATUS_DATE_FORMAT, $result->getGetValueResult()));
111
        }
112
113
        return $dataStatus;
114
    }
115
116
    /**
117
     * Get service status:
118
     * <p>
119
     * <b>0</b> - service unavailable <br>
120
     * <b>1</b> - service available <br>
121
     * <b>2</b> - service technical break <br>
122
     * </p>.
123
     *
124
     * @return int actual service status
125
     */
126
    public function serviceStatus(): int
127
    {
128
        $result = $this->apiClient->getValue(new GetValue(ParamName::SERVICE_STATUS));
129
130
        return (int) $result->getGetValueResult();
131
    }
132
133
    public function serviceMessage(): string
134
    {
135
        return $this->apiClient->getValue(new GetValue(ParamName::SERVICE_MESSAGE))->getGetValueResult();
136
    }
137
138
    /**
139
     * @throws NotFoundException
140
     *
141
     * @return SearchReport[]
142
     */
143
    public function getByNip(string $nip): array
144
    {
145
        return $this->search(
146
            new SearchData(
147
                new SearchParameters(null, null, $nip, null, null, null, null)
148
            )
149
        );
150
    }
151
152
    /**
153
     * @throws NotFoundException
154
     *
155
     * @return array|SearchReport[]
156
     */
157
    public function getByRegon(string $regon): array
158
    {
159
        return $this->search(
160
            new SearchData(
161
                new SearchParameters(null, null, null, null, $regon, null, null)
162
            )
163
        );
164
    }
165
166
    /**
167
     * @throws NotFoundException
168
     *
169
     * @return array|SearchReport[]
170
     */
171
    public function getByKrs(string $krs): array
172
    {
173
        return $this->search(
174
            new SearchData(
175
                new SearchParameters($krs, null, null, null, null, null, null)
176
            )
177
        );
178
    }
179
180
    /**
181
     * @param string[] $nips
182
     *
183
     * @throws NotFoundException
184
     *
185
     * @return array|SearchReport[]
186
     */
187
    public function getByNips(array $nips): array
188
    {
189
        $this->checkIdentifiersCount($nips);
190
191
        return $this->search(
192
            new SearchData(
193
                new SearchParameters(null, null, null, implode(',', $nips), null, null, null)
194
            )
195
        );
196
    }
197
198
    /**
199
     * @param string[] $krses
200
     *
201
     * @throws NotFoundException
202
     *
203
     * @return array|SearchReport[]
204
     */
205
    public function getByKrses(array $krses): array
206
    {
207
        $this->checkIdentifiersCount($krses);
208
209
        return $this->search(
210
            new SearchData(
211
                new SearchParameters(null, implode(',', $krses), null, null, null, null, null)
212
            )
213
        );
214
    }
215
216
    /**
217
     * @param string[] $regons
218
     *
219
     * @throws NotFoundException
220
     *
221
     * @return array|SearchReport[]
222
     */
223
    public function getByRegons9(array $regons): array
224
    {
225
        $this->checkIdentifiersCount($regons);
226
227
        return $this->search(
228
            new SearchData(
229
                new SearchParameters(null, null, null, null, null, null, implode(',', $regons))
230
            )
231
        );
232
    }
233
234
    /**
235
     * @param string[] $regons
236
     *
237
     * @throws NotFoundException
238
     *
239
     * @return array|SearchReport[]
240
     */
241
    public function getByregons14(array $regons): array
242
    {
243
        $this->checkIdentifiersCount($regons);
244
245
        return $this->search(
246
            new SearchData(
247
                new SearchParameters(null, null, null, null, null, implode(',', $regons), null)
248
            )
249
        );
250
    }
251
252
    /**
253
     * @throws InvalidReportTypeException
254
     *
255
     * @return array<int, array<string, string>>
256
     */
257
    public function getFullReport(SearchReport $searchReport, string $reportName): array
258
    {
259
        $this->ensureSession();
260
        $result = $this->apiClient->getFullReport(
261
            new GetFullReport(
262
                ReportRegonNumberMapper::getRegonNumberByReportName($searchReport, $reportName),
263
                $reportName
264
            ),
265
            $this->sessionId
266
        );
267
268
        return $result->getReport();
269
    }
270
271
    /**
272
     * @throws InvalidReportTypeException
273
     */
274
    public function getBulkReport(DateTimeImmutable $date, string $reportName): array
275
    {
276
        $this->ensureSession();
277
        if (!\in_array($reportName, BulkReportTypes::REPORTS, true)) {
278
            throw new InvalidReportTypeException(sprintf('Invalid report type: "%s", use one of allowed type: (%s)', $reportName, implode(', ', BulkReportTypes::REPORTS)));
279
        }
280
281
        return $this->apiClient->getBulkReport(
282
            new GetBulkReport($date->format('Y-m-d'), $reportName),
283
            $this->sessionId
284
        );
285
    }
286
287
    /**
288
     * Return message code if search not found record.
289
     */
290
    public function getMessageCode(): int
291
    {
292
        $this->ensureSession();
293
        $result = $this->apiClient->getValue(
294
            new GetValue(ParamName::MESSAGE_CODE),
295
            $this->sessionId
296
        );
297
298
        return (int) $result->getGetValueResult();
299
    }
300
301
    /**
302
     * Return message text id search not found record.
303
     */
304
    public function getMessage(): string
305
    {
306
        $this->ensureSession();
307
        $result = $this->apiClient->getValue(new GetValue(ParamName::MESSAGE), $this->sessionId);
308
309
        return $result->getGetValueResult();
310
    }
311
312
    public function getSessionStatus(): int
313
    {
314
        $this->ensureSession();
315
        $response = $this->apiClient->getValue(
316
            new GetValue(ParamName::SESSION_STATUS),
317
            $this->sessionId
318
        );
319
320
        return (int) $response->getGetValueResult();
321
    }
322
323
    private function checkIdentifiersCount(array $identifiers): void
324
    {
325
        if (\count($identifiers) > self::MAX_IDENTIFIERS) {
326
            throw new \InvalidArgumentException(sprintf('Too many identifiers. Maximum allowed is %d.', self::MAX_IDENTIFIERS));
327
        }
328
    }
329
330
    /**
331
     * @throws NotFoundException
332
     *
333
     * @return SearchReport[]
334
     */
335
    private function search(SearchData $searchData): array
336
    {
337
        $this->ensureSession();
338
        $result = $this->apiClient->searchData($searchData, $this->sessionId);
339
340
        return array_map(static fn (SearchResponseCompanyData $company): SearchReport => new SearchReport($company), $result->getDaneSzukajResult());
341
    }
342
343
    private function ensureSession(): void
344
    {
345
        if (!isset($this->sessionId)) {
346
            throw new \BadMethodCallException('Session is not started. Call login() first.');
347
        }
348
    }
349
}
350