Repository navigation
Expand file tree
/
Copy pathIntegrityClient.php
More file actions
1772 lines (1591 loc) · 57.9 KB
/
Copy pathIntegrityClient.php
File metadata and controls
1772 lines (1591 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* Integrity API PHP Client
*
* A PHP REST client for the Integrity WordPress plugin API.
* Provides access to Groups, Meetings, Positions, Members,
* and Intergroup Meetings from the Unity plugin.
*
* Authentication: Bearer token via Authorization header
* Base URL format: https://your-wordpress-site.com/wp-json/integrity/v1
*
* @see https://github.com/your-org/integrity
*/
// ---------------------------------------------------------------------------
// Response DTOs
// ---------------------------------------------------------------------------
/**
* Rate limit information included in every authenticated response.
*/
class RateLimit
{
public function __construct(
public readonly int $limit,
public readonly int $remaining,
public readonly int $reset,
) {}
public function resetDateTime(): \DateTimeImmutable
{
return new \DateTimeImmutable('@' . $this->reset);
}
}
/**
* Pagination metadata returned in list responses.
*/
class PaginationMeta
{
public function __construct(
public readonly int $total,
public readonly int $page,
public readonly int $perPage,
public readonly int $totalPages,
) {}
}
/**
* Generic API response wrapping a single item.
*
* @template T
*/
class ApiResponse
{
/**
* @param bool $success
* @param T|null $data
* @param string|null $errorCode
* @param string|null $errorMessage
* @param int $httpStatus
* @param RateLimit|null $rateLimit
*/
public function __construct(
public readonly bool $success,
public readonly mixed $data,
public readonly ?string $errorCode,
public readonly ?string $errorMessage,
public readonly int $httpStatus,
public readonly ?RateLimit $rateLimit = null,
) {}
}
/**
* Generic API response wrapping a list of items.
*
* @template T
*/
class ApiListResponse
{
/**
* @param bool $success
* @param T[] $data
* @param PaginationMeta|null $meta
* @param string|null $errorCode
* @param string|null $errorMessage
* @param int $httpStatus
* @param RateLimit|null $rateLimit
*/
public function __construct(
public readonly bool $success,
public readonly array $data,
public readonly ?PaginationMeta $meta,
public readonly ?string $errorCode,
public readonly ?string $errorMessage,
public readonly int $httpStatus,
public readonly ?RateLimit $rateLimit = null,
) {}
}
// ---------------------------------------------------------------------------
// Model classes
// ---------------------------------------------------------------------------
class ContributionOptions
{
public function __construct(
public readonly ?string $venmo,
public readonly ?string $paypal,
public readonly ?string $square,
public readonly bool $hasOptions,
) {}
}
class Contact
{
public function __construct(
public readonly string $name,
public readonly string $email,
public readonly string $phone,
public readonly string $updated,
) {}
}
class Location
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $address,
public readonly string $city,
public readonly string $state,
public readonly string $postalCode,
public readonly string $country,
public readonly string $region,
public readonly string $notes,
public readonly string $link,
public readonly ?float $latitude,
public readonly ?float $longitude,
public readonly string $timezone,
public readonly string $formattedAddress,
public readonly string $updated,
) {}
}
class Meeting
{
/** @param Contact[] $contacts */
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $slug,
public readonly ?Location $location,
public readonly string $url,
public readonly ?int $day,
public readonly string $dayOfWeek,
public readonly string $time,
public readonly string $endTime,
public readonly array $types,
public readonly string $state,
public readonly bool $isOnline,
public readonly string $onlineLink,
public readonly string $onlineNotes,
public readonly array $contacts,
public readonly array $meta,
public readonly string $updated,
) {}
}
class Group
{
/**
* @param Contact[] $contacts
* @param int[]|Meeting[] $meetingIds IDs or full Meeting objects depending on expand flag
*/
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly string $email,
public readonly string $phone,
public readonly string $website,
public readonly string $link,
public readonly string $notes,
public readonly string $groupEmail,
public readonly ?int $districtId,
public readonly string $lastContact,
public readonly array $meetingIds,
public readonly array $contacts,
public readonly ContributionOptions $contributionOptions,
public readonly string $updated,
) {}
}
class Position
{
public function __construct(
public readonly int $id,
public readonly string $longName,
public readonly string $shortDescription,
public readonly string $summary,
public readonly string $email,
public readonly ?int $minimumSobriety,
public readonly ?int $termYears,
public readonly string $link,
public readonly string $updated,
) {}
}
class Member
{
public function __construct(
public readonly int $id,
public readonly string $anonymousName,
public readonly string $personalEmail,
public readonly string $mobileNumber,
public readonly bool $showAnonymousName,
public readonly bool $showMemberProfile,
public readonly string $anonymousProfile,
public readonly ?int $homeGroupId,
public readonly string $homeGroupName,
public readonly bool $isGsr,
public readonly string $meetingPo,
public readonly ?int $intergroupPositionId,
public readonly string $intergroupPositionName,
public readonly string $intergroupPositionRotation,
public readonly string $link,
public readonly string $updated,
/**
* GDPR compliance state for the member.
*
* Null when talking to a server that pre-dates the compliance
* endpoint and therefore omits the gdpr_compliance object from
* its response. New servers always populate it.
*/
public readonly ?GdprCompliance $gdprCompliance = null,
/**
* The member's landline number.
*
* Masked like the mobile unless the key holds `members:clear`, and
* empty against a server that pre-dates the field.
*
* Appended rather than placed beside mobileNumber for the same
* reason gdprCompliance was: every parameter before it is required,
* so inserting mid-list would rebind every positional argument
* after it.
*/
public readonly string $landlineNumber = '',
/**
* Which of the two numbers to ring — "Mobile" or "Landline".
*
* Never masked: it names an option rather than a number. A member
* with no landline is always "Mobile"; the server settles that, so
* this can be read at face value. Left a string rather than an enum
* so a value from a newer server degrades instead of throwing.
*/
public readonly string $preferredContact = 'Mobile',
) {}
}
/**
* GDPR compliance state recorded for a member.
*
* `acceptedAt` is the raw ISO 8601 string returned by the server (e.g.
* "2026-04-27T15:45:00.000Z") or an empty string when no acceptance
* has ever been recorded. Callers that need a DateTimeImmutable should
* parse with `new DateTimeImmutable($member->gdprCompliance->acceptedAt)`
* after a non-empty check.
*
* When `accepted` is false, `version`, `method`, and `statement` are
* cleared by the server; only `accepted` and `acceptedAt` carry
* meaningful values for revocations.
*/
class GdprCompliance
{
public function __construct(
public readonly bool $accepted,
public readonly string $acceptedAt,
public readonly string $version,
public readonly string $method,
public readonly string $statement,
) {}
}
class GroupAttendee
{
public function __construct(
public readonly int $id,
public readonly string $name,
) {}
}
class OfficerAttendee
{
public function __construct(
public readonly int $id,
public readonly string $name,
) {}
}
class IntergroupMeeting
{
/**
* @param int[] $groupAttendeeIds
* @param GroupAttendee[] $groupAttendees
* @param int[] $officersAttendingIds
* @param OfficerAttendee[] $officersAttending
*/
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly string $date,
public readonly array $groupAttendeeIds,
public readonly array $groupAttendees,
public readonly array $officersAttendingIds,
public readonly array $officersAttending,
public readonly string $updated,
) {}
}
class HealthStatus
{
public function __construct(
public readonly string $status,
public readonly string $timestamp,
public readonly string $version,
public readonly bool $unityAvailable,
) {}
public function isHealthy(): bool
{
return $this->status === 'healthy';
}
}
// ---------------------------------------------------------------------------
// Request parameter objects
// ---------------------------------------------------------------------------
class GroupsQuery
{
public function __construct(
public int $page = 1,
public int $perPage = 100,
public ?string $search = null,
public ?int $districtId = null,
public bool $expandMeetings = false,
) {}
}
class MeetingsQuery
{
/**
* @param int|null $day 0 = Sunday … 6 = Saturday
* @param bool|null $online true = online only, false = in-person only
*/
public function __construct(
public int $page = 1,
public int $perPage = 100,
public ?int $day = null,
public ?bool $online = null,
public ?int $groupId = null,
public ?string $search = null,
) {}
}
class PositionsQuery
{
public function __construct(
public int $page = 1,
public int $perPage = 100,
public ?string $search = null,
) {}
}
class MembersQuery
{
public function __construct(
public int $page = 1,
public int $perPage = 100,
public ?string $search = null,
public ?int $homeGroupId = null,
) {}
}
class IntergroupMeetingsQuery
{
public function __construct(
public int $page = 1,
public int $perPage = 100,
public ?string $dateFrom = null, // Y-m-d
public ?string $dateTo = null, // Y-m-d
) {}
}
class UpdateMemberRequest
{
public function __construct(
public ?string $anonymousName = null,
public ?string $personalEmail = null,
public ?string $mobileNumber = null,
public ?bool $showAnonymousName = null,
public ?bool $showMemberProfile = null,
public ?string $anonymousProfile = null,
public ?int $homeGroupId = null,
public ?bool $isGsr = null,
public ?int $intergroupPositionId = null,
public ?string $intergroupPositionRotation = null, // Y-m-d or empty string
public ?string $landlineNumber = null,
// "Mobile" or "Landline". The server rejects anything else, and
// ignores this entirely for a member with no landline.
public ?string $preferredContact = null,
) {}
/**
* The JSON body for POST /members/{id}/update — supplied fields only.
*
* @return array<string,mixed>
*/
public function toPayload(): array
{
$payload = [];
if ($this->anonymousName !== null) {
$payload['anonymous_name'] = $this->anonymousName;
}
if ($this->personalEmail !== null) {
$payload['personal_email'] = $this->personalEmail;
}
if ($this->mobileNumber !== null) {
$payload['mobile_number'] = $this->mobileNumber;
}
if ($this->showAnonymousName !== null) {
$payload['show_anonymous_name'] = $this->showAnonymousName;
}
if ($this->showMemberProfile !== null) {
$payload['show_member_profile'] = $this->showMemberProfile;
}
if ($this->anonymousProfile !== null) {
$payload['anonymous_profile'] = $this->anonymousProfile;
}
if ($this->homeGroupId !== null) {
$payload['home_group_id'] = $this->homeGroupId;
}
if ($this->isGsr !== null) {
$payload['is_gsr'] = $this->isGsr;
}
if ($this->intergroupPositionId !== null) {
$payload['intergroup_position_id'] = $this->intergroupPositionId;
}
if ($this->intergroupPositionRotation !== null) {
$payload['intergroup_position_rotation'] = $this->intergroupPositionRotation;
}
if ($this->landlineNumber !== null) {
$payload['landline_number'] = $this->landlineNumber;
}
if ($this->preferredContact !== null) {
$payload['preferred_contact'] = $this->preferredContact;
}
return $payload;
}
}
class CreateMemberRequest
{
public function __construct(
public string $anonymousName,
public ?string $personalEmail = null,
public ?string $mobileNumber = null,
public ?int $homeGroupId = null,
public ?bool $isGsr = null,
public ?int $intergroupPositionId = null,
public ?string $landlineNumber = null,
// "Mobile" or "Landline"; see UpdateMemberRequest.
public ?string $preferredContact = null,
) {}
/**
* The JSON body for POST /members/create.
*
* @return array<string,mixed>
*/
public function toPayload(): array
{
$payload = ['anonymous_name' => $this->anonymousName];
if ($this->personalEmail !== null) {
$payload['personal_email'] = $this->personalEmail;
}
if ($this->mobileNumber !== null) {
$payload['mobile_number'] = $this->mobileNumber;
}
if ($this->homeGroupId !== null) {
$payload['home_group_id'] = $this->homeGroupId;
}
if ($this->isGsr !== null) {
$payload['is_gsr'] = $this->isGsr;
}
if ($this->intergroupPositionId !== null) {
$payload['intergroup_position_id'] = $this->intergroupPositionId;
}
if ($this->landlineNumber !== null) {
$payload['landline_number'] = $this->landlineNumber;
}
if ($this->preferredContact !== null) {
$payload['preferred_contact'] = $this->preferredContact;
}
return $payload;
}
}
/**
* Request body for POST /members/{id}/compliance.
*
* `accepted` is required (it's the action being recorded — either
* acceptance or revocation). All other fields are optional and have
* sensible server-side defaults:
*
* - `acceptedAt` — defaults to "now" (UTC) when null. Accepts any
* DateTime-parseable string; the server normalises
* to UTC `Y-m-d H:i:s` before storage.
* - `version` — only persisted when `accepted` is true.
* - `method` — defaults to "api" when null and `accepted` is true.
* Ignored on revocations.
* - `policyId` — WordPress post ID of the privacy policy the member
* accepted. The server looks it up through Scrutiny's
* PrivacyPolicyRepository and persists the policy body
* as the recorded statement. Only persisted when
* `accepted` is true; ignored on revocations.
* Replaces the previous `statement` field — clients
* no longer send the policy body on the wire.
*
* On revocation (`accepted = false`), the server clears version,
* method, and statement regardless of what is sent — they belonged
* to the now-revoked acceptance and no longer apply.
*/
class RecordComplianceRequest
{
public function __construct(
public bool $accepted,
public ?string $acceptedAt = null,
public ?string $version = null,
public ?string $method = null,
public ?int $policyId = null,
) {}
/**
* The JSON body for POST /members/{id}/compliance.
*
* @return array<string,mixed>
*/
public function toPayload(): array
{
$payload = ['accepted' => $this->accepted];
if ($this->acceptedAt !== null) {
$payload['accepted_at'] = $this->acceptedAt;
}
if ($this->version !== null) {
$payload['version'] = $this->version;
}
if ($this->method !== null) {
$payload['method'] = $this->method;
}
if ($this->policyId !== null) {
$payload['policy_id'] = $this->policyId;
}
return $payload;
}
}
class RegisterGroupRequest
{
public function __construct(
public int $groupId,
public string $gsrName,
public int $memberId = 0,
public bool $gsrProxy = false,
public string $gsrProxyName = '',
) {}
/** @return array<string,mixed> */
public function toPayload(): array
{
return [
'group_id' => $this->groupId,
'gsr_name' => $this->gsrName,
'member_id' => $this->memberId,
'gsr_proxy' => $this->gsrProxy,
'gsr_proxy_name' => $this->gsrProxyName,
];
}
}
class RegisterOfficerRequest
{
public function __construct(
public int $officerId,
public string $positionName,
public string $officerName,
) {}
/** @return array<string,mixed> */
public function toPayload(): array
{
return [
'officer_id' => $this->officerId,
'position_name' => $this->positionName,
'officer_name' => $this->officerName,
];
}
}
// ---------------------------------------------------------------------------
// Batch
// ---------------------------------------------------------------------------
/**
* The result of a batch sent through WordPress core's /batch/v1.
*
* `responses` holds one ApiResponse per queued request, in the order they
* were queued. When the batch was sent with `requireAllValid` and any request
* failed validation, nothing ran: `validationFailed` is true, the requests
* that failed carry their error, and the rest are null.
*
* `errorCode` / `errorMessage` are set only when the batch as a whole was
* refused (e.g. more requests than the server's batch limit), in which case
* `responses` is empty.
*/
class BatchResponse
{
/**
* @param list<ApiResponse|null> $responses
*/
public function __construct(
public readonly bool $success,
public readonly array $responses,
public readonly bool $validationFailed,
public readonly int $httpStatus,
public readonly ?string $errorCode = null,
public readonly ?string $errorMessage = null,
) {}
/**
* The responses that did not succeed, keyed by their position in the batch.
*
* @return array<int, ApiResponse>
*/
public function failures(): array
{
return array_filter(
$this->responses,
static fn (?ApiResponse $r): bool => $r !== null && !$r->success,
);
}
}
/**
* A set of write requests sent to the server in one HTTP call.
*
* Only the write endpoints can be batched — WordPress core accepts POST, PUT,
* PATCH and DELETE in a batch, never GET. Build one with
* IntegrityClient::batch(), queue requests, then send():
*
* $result = $client->batch()
* ->updateMember(5, new UpdateMemberRequest(mobileNumber: '07700 900123'))
* ->registerGroup(7, new RegisterGroupRequest(groupId: 12, gsrName: 'John D.'))
* ->send();
*
* The API key is sent once, on the batch, and the server validates it once.
* Each request is still checked against its own permission and counts once
* against the key's rate limit.
*/
class IntegrityBatch implements \Countable
{
/**
* The batch limit the Integrity plugin sets on the site. Core's own
* default is 25; Integrity raises it through rest_get_max_batch_size.
*/
public const DEFAULT_MAX_SIZE = 256;
/** @var list<array{path: string, body: array<string,mixed>, member: bool}> */
private array $requests = [];
/**
* @param bool $requireAllValid Run nothing unless every request passes the
* server's argument validation.
* @param int $maxSize Lower only if the site overrides Integrity's limit.
*/
public function __construct(
private readonly IntegrityClient $client,
private readonly bool $requireAllValid = false,
private readonly int $maxSize = self::DEFAULT_MAX_SIZE,
) {}
public function updateMember(int $id, UpdateMemberRequest $req): static
{
return $this->add("/members/{$id}/update", $req->toPayload(), member: true);
}
public function createMember(CreateMemberRequest $req): static
{
return $this->add('/members/create', $req->toPayload(), member: true);
}
public function recordCompliance(int $id, RecordComplianceRequest $req): static
{
return $this->add("/members/{$id}/compliance", $req->toPayload(), member: true);
}
public function registerGroup(int $meetingId, RegisterGroupRequest $req): static
{
return $this->add("/intergroup-meetings/{$meetingId}/register-group", $req->toPayload());
}
public function unregisterGroup(int $meetingId, int $groupId): static
{
return $this->add("/intergroup-meetings/{$meetingId}/unregister-group", ['group_id' => $groupId]);
}
public function registerOfficer(int $meetingId, RegisterOfficerRequest $req): static
{
return $this->add("/intergroup-meetings/{$meetingId}/register-officer", $req->toPayload());
}
public function unregisterOfficer(int $meetingId, int $officerId): static
{
return $this->add("/intergroup-meetings/{$meetingId}/unregister-officer", ['officer_id' => $officerId]);
}
public function count(): int
{
return count($this->requests);
}
/**
* Send every queued request in one call.
*
* @throws IntegrityClientException On a transport or decoding failure
*/
public function send(): BatchResponse
{
return $this->client->sendBatch($this->requests, $this->requireAllValid);
}
/**
* @param array<string,mixed> $body
*/
private function add(string $path, array $body, bool $member = false): static
{
if (count($this->requests) >= $this->maxSize) {
throw new \LengthException(
"A batch holds at most {$this->maxSize} requests; send this one and start another."
);
}
$this->requests[] = ['path' => $path, 'body' => $body, 'member' => $member];
return $this;
}
}
// ---------------------------------------------------------------------------
// Exception
// ---------------------------------------------------------------------------
class IntegrityClientException extends \RuntimeException
{
public function __construct(
string $message,
public readonly int $httpStatus = 0,
public readonly ?string $errorCode = null,
?\Throwable $previous = null,
) {
parent::__construct($message, $httpStatus, $previous);
}
}
// ---------------------------------------------------------------------------
// Main client
// ---------------------------------------------------------------------------
class IntegrityClient
{
private const REST_ROOT = '/wp-json';
private const API_NAMESPACE = 'integrity/v1';
private const API_PATH = self::REST_ROOT . '/' . self::API_NAMESPACE;
private const DEFAULT_TIMEOUT = 30;
private string $baseUrl;
private string $apiKey;
private int $timeout;
private ?\CurlHandle $curlHandle = null;
/**
* @param string $baseUrl WordPress site root URL, e.g. "https://example.com"
* @param string $apiKey Integrity API key starting with "int_"
* @param int $timeout HTTP request timeout in seconds
*/
public function __construct(string $baseUrl, string $apiKey, int $timeout = self::DEFAULT_TIMEOUT)
{
if (empty($baseUrl)) {
throw new \InvalidArgumentException('baseUrl must not be empty');
}
if (empty($apiKey)) {
throw new \InvalidArgumentException('apiKey must not be empty');
}
$this->baseUrl = rtrim($baseUrl, '/');
$this->apiKey = $apiKey;
$this->timeout = $timeout;
}
public function __destruct()
{
$this->close();
}
/** Release the cURL handle if open. */
public function close(): void
{
if ($this->curlHandle !== null) {
curl_close($this->curlHandle);
$this->curlHandle = null;
}
}
// -----------------------------------------------------------------------
// Health
// -----------------------------------------------------------------------
/**
* Check API health. Does not require authentication.
*
* @return ApiResponse<HealthStatus>
*/
public function checkHealth(): ApiResponse
{
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', '/health');
$health = new HealthStatus(
status: $body['status'] ?? 'unknown',
timestamp: $body['timestamp'] ?? '',
version: $body['version'] ?? '',
unityAvailable: (bool) ($body['unity_available'] ?? false),
);
return new ApiResponse(
success: $status < 400,
data: $health,
errorCode: null,
errorMessage: null,
httpStatus: $status,
rateLimit: null,
);
}
// -----------------------------------------------------------------------
// Groups
// -----------------------------------------------------------------------
/**
* List groups with optional filtering and pagination.
*
* @return ApiListResponse<Group>
*/
public function getGroups(GroupsQuery $query = new GroupsQuery()): ApiListResponse
{
$params = [
'page' => $query->page,
'per_page' => $query->perPage,
];
if ($query->search !== null) {
$params['search'] = $query->search;
}
if ($query->districtId !== null) {
$params['district_id'] = $query->districtId;
}
if ($query->expandMeetings) {
$params['expand'] = 'meetings';
}
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', '/groups', $params);
return $this->buildListResponse(
$body,
$status,
$headers,
fn (array $item) => $this->hydrateGroup($item),
);
}
/**
* Get a single group by ID.
*
* @return ApiResponse<Group>
*/
public function getGroup(int $id, bool $expandMeetings = false): ApiResponse
{
$params = $expandMeetings ? ['expand' => 'meetings'] : [];
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', "/groups/{$id}", $params);
return $this->buildSingleResponse(
$body,
$status,
$headers,
fn (array $item) => $this->hydrateGroup($item),
);
}
// -----------------------------------------------------------------------
// Meetings
// -----------------------------------------------------------------------
/**
* List meetings with optional filtering and pagination.
*
* @return ApiListResponse<Meeting>
*/
public function getMeetings(MeetingsQuery $query = new MeetingsQuery()): ApiListResponse
{
$params = [
'page' => $query->page,
'per_page' => $query->perPage,
];
if ($query->day !== null) {
$params['day'] = $query->day;
}
if ($query->online !== null) {
$params['online'] = $query->online ? 'true' : 'false';
}
if ($query->groupId !== null) {
$params['group_id'] = $query->groupId;
}
if ($query->search !== null) {
$params['search'] = $query->search;
}
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', '/meetings', $params);
return $this->buildListResponse(
$body,
$status,
$headers,
fn (array $item) => $this->hydrateMeeting($item),
);
}
/**
* Get a single meeting by ID.
*
* @return ApiResponse<Meeting>
*/
public function getMeeting(int $id): ApiResponse
{
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', "/meetings/{$id}");
return $this->buildSingleResponse(
$body,
$status,
$headers,
fn (array $item) => $this->hydrateMeeting($item),
);
}
// -----------------------------------------------------------------------
// Positions
// -----------------------------------------------------------------------
/**
* List positions with optional filtering and pagination.
*
* @return ApiListResponse<Position>
*/
public function getPositions(PositionsQuery $query = new PositionsQuery()): ApiListResponse
{
$params = [
'page' => $query->page,
'per_page' => $query->perPage,
];
if ($query->search !== null) {
$params['search'] = $query->search;
}
['body' => $body, 'status' => $status, 'headers' => $headers] =
$this->request('GET', '/positions', $params);