-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbexio.php
1220 lines (1087 loc) · 32.8 KB
/
bexio.php
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
/**
* @author Etienne Bagnoud <[email protected]>
* @license MIT
* @copyright 2023 Etienne Bagnoud
*
*/
namespace BizCuit;
require(__DIR__ . '/bxquery.php');
require(__DIR__ . '/bxobject.php');
use BizCuit\BXObject\BXObject;
use BizCuit\BXQuery\BXQuery;
use CURLFile;
use CurlHandle;
use Exception;
use stdClass;
/**
* Base class containing cURL operations.
*/
class BexioCTX {
public const endpoint = 'https://api.bexio.com/';
protected CurlHandle $c;
protected array $headers = [];
protected object $values;
protected string $token;
protected array $ratelimits;
protected int $sleepPercent;
/**
* Create the context with API token needed to access endpoints
*
* Of all authentications available, only the API token is avaible.
*
* @link https://docs.bexio.com/#section/Authentication/API-Tokens
* @param String $token The token.
*/
function __construct(String $token) {
$this->c = curl_init();
$this->token = $token;
$this->headers = [
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer ' . $token
];
$this->values = new stdClass();
$this->method = 'get';
$this->ratelimits = [
'remaining' => 0,
'limit' => 0,
'reset' => 0
];
$this->sleepPercent = 0;
}
private function set_url (string $url):void {
// remove leading slash
while(substr($url, 0, 1) === '/') { $url = substr($url, 1); }
// remove double slashes (bexio api return an error else)
$url = str_replace('//', '/', $url);
curl_setopt($this->c, CURLOPT_URL, $this::endpoint . $url);
}
private function set_method(string $method = 'get'):void {
switch(strtolower($method)) {
default:
case 'get': curl_setopt($this->c, CURLOPT_HTTPGET, true); break;
case 'post': curl_setopt($this->c, CURLOPT_POST, true); break;
case 'delete': curl_setopt($this->c, CURLOPT_CUSTOMREQUEST, 'DELETE'); break;
case 'put': curl_setopt($this->c, CURLOPT_CUSTOMREQUEST, 'PUT'); break;
case 'patch': curl_setopt($this->c, CURLOPT_CUSTOMREQUEST, 'PATCH'); break;
case 'head': curl_setopt($this->c, CURLOPT_CUSTOMREQUEST, 'HEAD'); break;
}
}
/**
* Set the request body if any.
*/
private function set_body (string $body = ''):void {
if (strlen($body) < 0) { return; }
curl_setopt($this->c, CURLOPT_POSTFIELDS, $body);
}
private function reset():void {
unset($this->url);
unset($this->body);
curl_reset($this->c);
}
function get_token ():string {
return $this->token;
}
function __set(string $name, mixed $value):void {
switch ($name) {
case 'url':
case 'method':
case 'body':
case 'user_id':
case 'owner_id':
$this->values->{$name} = $value;
break;
}
}
function __get(string $name):mixed {
switch ($name) {
default: return null;
case 'url':
case 'method':
case 'body':
case 'user_id':
case 'owner_id':
if (!property_exists($this->values, $name)) { return ''; }
return $this->values->{$name};
}
}
function __isset(string $name):bool {
switch ($name) {
default: return false;
case 'url':
case 'method':
case 'body':
case 'user_id':
case 'owner_id':
return property_exists($this->values, $name);
}
}
function __unset(string $name):void {
switch($name) {
default: return;
case 'url':
case 'method':
case 'body':
case 'user_id':
case 'owner_id':
unset($this->values->{$name});
}
}
/**
* Set the sleep percent for each request. The API give back the time remaining
* and the number of requests still available in that time frame. This give
* us a number of request per second. By setting a value > 0, we will sleep
* for the given percent of the time remaining.
* @param int $percent
* @return void
*/
function setSleep (int $percent) {
$this->sleepPercent = $percent;
}
function handle_result (string $data, int $code, string $type):stdClass|string|Array {
switch($code) {
case 200:
case 201:
if (strcasecmp($type, 'application/json') === 0) {
return json_decode($data);
}
return $data;
case 304: throw new Exception('The resource has not been changed', $code, new Exception($data));
case 400: throw new Exception('The request parameters are invalid', $code, new Exception($data));
case 401: throw new Exception('The bearer token or the provided api key is invalid', $code, new Exception($data));
case 403: throw new Exception('You do not possess the required rights to access this resource',$code, new Exception($data));
case 404: throw new Exception('The resource could not be found', $code, new Exception($data));
case 411: throw new Exception('Length Required', $code, new Exception($data));
case 415: throw new Exception('The data could not be processed or the accept header is invalid', $code, new Exception($data));
case 422: throw new Exception('Could not save the entity', $code, new Exception($data));
case 429: throw new Exception('Too many requests', $code, new Exception($data));
case 500: throw new Exception('An unexpected condition was encountered', $code, new Exception($data));
case 503: throw new Exception('The server is not available (maintenance work)', $code, new Exception($data));
default: throw new Exception('Error with code ' . $code, $code, new Exception($data));
}
}
/**
* Execute the request.
* @return stdClass|string|Array The JSON response decoded or the raw value
* @throws Exception A generic exception with code matching the HTTP error
* code from the upstream API if any.
*/
function fetch ():stdClass|string|Array {
try {
$ratelimits = [
'remaining' => 0,
'limit' => 0,
'reset' => 0
];
curl_setopt($this->c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->c, CURLOPT_HEADERFUNCTION,
function (CurlHandle $curl, string $header) use (&$ratelimits) {
$len = strlen($header);
$parts = explode(':', $header);
if (count($parts) < 2) { return $len; }
$parts[0] = strtolower(trim($parts[0]));
switch($parts[0]) {
default: return $len;
case 'ratelimit-limit':
case 'ratelimit-remaining':
case 'ratelimit-reset':
$value = explode('-', $parts[0]);
$type = array_pop($value);
$ratelimits[$type] = intval(trim($parts[1]));
break;
}
return $len;
}
);
$this->set_method($this->method);
$this->set_url($this->url);
$headers = $this->headers;
if ($this->method !== 'get' && $this->method !== 'head') { $this->set_body($this->body); }
/* An API bug can be triggered if you send a GET without
* Content-Length set to 0
*/
if (strlen($this->body) <= 0) {
$headers = array_merge($this->headers, ['Content-Length: 0']);
}
curl_setopt($this->c, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($this->c);
if ($data === false) { throw new Exception(curl_error($this->c), curl_errno($this->c)); }
$code = curl_getinfo($this->c, CURLINFO_HTTP_CODE);
$type = curl_getinfo($this->c, CURLINFO_CONTENT_TYPE);
$this->ratelimits = $ratelimits;
if ($this->sleepPercent > 0 && $ratelimits['remaining'] > 0 && $ratelimits['reset'] > 0) {
$sleep = (($ratelimits['reset'] * 1000000) / $ratelimits['remaining']) * $this->sleepPercent / 100;
usleep($sleep);
}
$this->reset();
} catch (Exception $e) {
throw new Exception('Program error', 0, $e);
}
return $this->handle_result($data, $code, $type);
}
function getCurrentLimits():array {
return $this->ratelimits;
}
}
/**
* Base class for enpdoints.
*/
class BexioAPI {
protected string $endpoint;
protected Int|null $userid = null;
protected Int|null $ownerid = null;
protected BexioCTX $ctx;
/**
* Create withing the given context.
*
* @param BexioCTX $ctx The context in which the API will work.
*
*/
function __construct(BexioCTX $ctx) {
$this->ctx = $ctx;
$this->endpoint = $ctx::endpoint;
}
/**
* Set current user id.
*
* Some items, at creation, need a user id and/or an owner id. Setting this
* here allows to automatically add this to the item. If only user is set,
* when owner is needed it would be set to user.
*
* @param Int $userid The id of the user for all creation from now on.
* @return void
*
*/
function setCurrentUser (Int $userid):void {
$this->userid = $userid;
}
/**
* Set current owner id.
*
* Some items, at creation, need a user id and/or an owner id. This set the
* owner.
*
* @param Int $ownerid The id of the owner for all creation from now on.
* @return void
*
*/
function setCurrentOwner (Int $ownerid) {
$this->ownerid = $ownerid;
}
/**
* Get the current type.
*
* The current type correspond to an endpoint in the upstream API.
*
* @return string The type name
*/
function getType():string {
$parts = explode('\\', $this->className);
return array_pop($parts);
}
}
trait tBexioV2Api {
const api_version = '2.0';
}
trait tBexioV3Api {
const api_version = '3.0';
}
trait tBexioV4Api {
const api_version = '4.0';
/**
* Search request for version 4 of the API.
*
* @see tBexioCollection::search()
*/
function search (BXQuery $query, Int|array $offset = 0, Int $limit = 100):array {
if (is_array($offset)) {
$limit = $offset['limit'] ?? 100;
$offset = $offset['offset'] ?? 0;
}
$offset = ($offset / $limit) + 1;
$search_str_array = ['page' => $offset, 'limit' => $limit, 'search_term' => null ];
$fields = [];
foreach($query->getRawQuery() as $query) {
$field = urlencode($query->field);
$term = urlencode($query->value);
if (in_array($query->field, $this->search_fields)) {
if (in_array($field, $fields)) { continue; }
$fields[] = $field;
if (!$search_str_array['search_term']) {
$search_str_array['search_term'] = $term;
}
$search_str_array[$field] = $term;
continue;
}
if (!isset($search_str_array[$field])) { $search_str_array[$field] = $term; }
}
if (!$search_str_array['search_term']) {
unset($search_str_array['search_term']);
}
$a = [];
foreach($search_str_array as $k => $v) { $a[] = $k . '=' . $v; }
$qs = '?' . join('&', $a);
$this->ctx->url = $this::api_version . '/' . $this::type . $qs;
$this->ctx->method = 'get';
$result = $this->ctx->fetch();
return array_map(
fn(array|stdClass $e) => is_array($e)
? new $this->className((object)$e)
: new $this->className($e),
$result->data
);
}
/**
* List request for version 4 of the API.
*
* @see tBexioCollection::list()
*/
function list (Int|array $offset, Int $limit = 0):array {
if (is_array($offset)) {
$limit = $offset['limit'] ?? 100;
$offset = $offset['offset'] ?? 0;
}
return $this->search($this->newQuery(), $offset, $limit);
}
/**
* Get ID name for version 4 of the API.
*
* @see tBexioCollection::getIdName()
*/
function getIdName ():string {
$c = $this->className;
return $c::ID;
}
/**
* Create new query for version 4 of the API.
*
* @see tBexioCollection::newQuery()
*/
function newQuery ():BXquery {
return new $this->query();
}
}
trait tBexioQuerySearchV3Api {
/**
* Search request for version 3 that use query string (instead of POST body) of the API.
*
* @see tBexioCollection::search()
*/
function search (?BXQuery $query, Int|array $offset = 0, Int $limit = 100):array {
if (is_array($offset)) {
$limit = $offset['limit'] ?? 100;
$offset = $offset['offset'] ?? 0;
}
$search_str_array = ['offset' => $offset, 'limit' => $limit ];
if ($query) {
foreach($query->getRawQuery() as $query) {
$field = urlencode($query->field);
$term = urlencode($query->value);
if (!isset($search_str_array[$field])) { $search_str_array[$field] = $term; }
}
}
$a = [];
foreach($search_str_array as $k => $v) { $a[] = $k . '=' . $v; }
$qs = '?' . join('&', $a);
$this->ctx->url = $this::api_version . '/' . $this::type . $qs;
$this->ctx->method = 'get';
$result = $this->ctx->fetch();
return array_map(
fn(array|stdClass $e) => is_array($e)
? new $this->className((object)$e)
: new $this->className($e),
$result
);
}
/**
* List request for version 3 that use query string of the API.
*
* @see tBexioCollection::list()
*/
function list (Int|array $offset, Int $limit = 0):array {
if (is_array($offset)) {
$limit = $offset['limit'] ?? 100;
$offset = $offset['offset'] ?? 0;
}
return $this->search(null, $offset, $limit);
}
function newQuery() :BXquery {
return new $this->query;
}
}
trait tBexioUpload {
function upload (string $filepath):stdClass|string|Array {
$headers = [
'Accept: application/json',
'Authorization: Bearer ' . $this->ctx->get_token()
];
try {
$c = curl_init();
$curlfile = new CURLFile($filepath, mime_content_type($filepath), basename($filepath));
$url = $this::api_version . '/' . $this::type;
while(substr($url, 0, 1) === '/') { $url = substr($url, 1); }
$url = str_replace('//', '/', $url);
curl_setopt($c, CURLOPT_URL, $this->ctx::endpoint . $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS,['file' => $curlfile]);
curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($c);
$code = curl_getinfo($c, CURLINFO_HTTP_CODE);
$type = curl_getinfo($c, CURLINFO_CONTENT_TYPE);
curl_close($c);
} catch (Exception $e) {
throw new Exception('Program error', 0, $e);
}
return $this->ctx->handle_result($data, $code, $type);
}
}
trait tBexioCollection {
/**
* Return the property name used as unique id for this collection.
* @return string ID name.
*
* @api
*/
function getIdName ():string {
$c = $this->className;
return $c::ID;
}
/**
* Create a new BXQuery object for this collection.
* @return BXquery The BXQuery valid for this collection.
*
* @api
*/
function newQuery ():BXquery {
return new $this->query();
}
function query_string (array|int $options, int $limit):string {
$qs = [];
if (is_array($options)) {
$qs = [
sprintf('offset=%d', $options['offset'] ?? 0),
sprintf('limit=%d', $options['limit'] ?? 100)
];
if (isset($options['order'])) {
if (is_string($options['order'])) {
$qs[] = sprintf('order_by=%s', $options['order']);
} else if (is_array($options['order'])) {
$qs[] = sprintf('order_by=%s', join(',', $options['order']));
}
}
} else {
$qs = [
sprintf('offset=%d', $options),
sprintf('limit=%d', $limit)
];
}
return implode('&', $qs);
}
/**
* Search the collection.
* @param BXQuery $query The query object.
* @param Int $offset Offset in the search result,
* @param Int $limit Max number of search resutl.
* @return BXObject[] Matching items in the collection.
*
* @api
*/
function search (BXQuery $query, array|Int $options = 0, Int $limit = 500):array {
if ($query->isWithAnyfields()) { return $this->search_with_anyfields($query); }
$this->ctx->url = self::api_version . '/' . self::type .'/search' . '?' . $this->query_string($options, $limit);
$this->ctx->body = $query->toJson();
$this->ctx->method = 'post';
return array_map(fn($e) => new $this->className($e), $this->ctx->fetch());
}
protected function compare (BXQuery $query, BXObject $e):bool {
$query = $query->getRawQueryLocal();
foreach ($query as $condition) {
switch ($condition->criteria) {
case '=': case 'equal':
if ($e->{$condition->field} != $condition->value) { return false; }
break;
case '!=': case 'not_equal':
if ($e->{$condition->field} == $condition->value) { return false; }
break;
case '>': case 'greater_than':
if ($e->{$condition->field} <= $condition->value) { return false; }
break;
case '<': case 'less_than':
if ($e->{$condition->field} >= $condition->value) { return false; }
break;
case '>=': case 'greater_equal':
if ($e->{$condition->field} < $condition->value) { return false; }
break;
case '<=': case 'less_equal':
if ($e->{$condition->field} > $condition->value) { return false; }
break;
case 'like':
if (strpos(strval($e->{$condition->field}), strval($condition->value)) === false) { return false; }
break;
case 'not_like':
if (strpos(strval($e->{$condition->field}), strval($condition->value)) !== false) { return false; }
break;
case 'is_null':
if (!is_null($e->{$condition->field})) { return false; }
break;
case 'not_null':
if (is_null($e->{$condition->field})) { return false; }
break;
case 'in':
if (!in_array($e->{$condition->field}, $condition->value)) { return false; }
break;
case 'not_in':
if (in_array($e->{$condition->field}, $condition->value)) { return false; }
break;
}
}
return true;
}
protected function search_with_anyfields (BXQuery $query):array {
$results = [];
$offset = 0;
$limit = 500;
$useList = empty($query->getRawQuery());
$query->unsetWithAnyfields();
do {
$batch = [];
if ($useList) {
$batch = $this->list([
'offset' => $offset,
'limit' => $limit,
'order' => 'id']);
} else {
$batch = $this->search($query, [
'offset' => $offset,
'limit' => $limit,
'order' => 'id']);
}
if (empty($batch)) { break; }
$results = array_merge(
$results,
array_filter($batch, fn($e) => $this->compare($query, $e))
);
$offset += $limit;
} while (true);
return $results;
}
/**
* List the collection.
* @param Int $offset Offset in the search result,
* @param Int $limit Max number of search result.
* @return BXObject[] Items in the collection.
*
* @api
*/
function list (array|Int $options = 0, Int $limit = 500):array {
$this->ctx->method = 'get';
$this->ctx->url = self::api_version . '/' . self::type . '?' . $this->query_string($options, $limit);
return array_map(fn($e) => new $this->className($e), $this->ctx->fetch());
}
}
trait tBexioObject {
/**
* Create a new BXObject.
* @return BXObject New empty BXObject.
*
* @api
*/
function new ():BXObject {
return new $this->className();
}
/**
* Delete an item in the collection.
* @param Int|String|BXObject $id The id or the object to delete.
* @return Bool True on success, false otherwise.
*
* @api
*/
function delete(Int|String|BXObject $id): Bool {
if ($id instanceof BXObject) {
$id = $id->getId();
}
$this->ctx->url = $this::api_version . '/' . $this::type . '/' . strval($id);
$this->ctx->method = 'delete';
return $this->ctx->fetch()->success;
}
/**
* Get an item from the collection
* @param Int|String|BXObject $id The id or the object to get.
* @param Array $options Options that can be passed as query string.
* @return BXObject The item as a BXObject.
*
* @api
*/
function get (Int|String|BXObject $id, array $options = []):BXObject {
if ($id instanceof BXObject) {
$id = $id->getId();
}
$this->ctx->method = 'get';
$this->ctx->url = $this::api_version .'/' . $this::type . '/' . strval($id);
$query = [];
foreach ($options as $name => $value) {
$query[] = urlencode(strval($name)) . '=' . urlencode(strval($value));
}
if (!empty($query)) {
$this->ctx->url .= '?' . join('&', $query);
}
return new $this->className($this->ctx->fetch());
}
/**
* Set an item in the collection
*
* Setting an item would create the item if it don't have an ID or overwrite
* the item if it has an ID.
*
* @param BXObject $content The object to be set.
* @return BXObject|false The item is returned as stored in collection or
* false in case of error
*
* @api
*/
function set (BXObject $content):BXObject|false {
if ($content->isReadonly()) { return false; }
/* try to fix user_id and owner_id if possible */
if (!is_null($this->ctx->user_id)) {
if ((!is_numeric($content->user_id) || is_null($content->user_id)) && in_array('user_id', $content::createProperties)) {
$content->user_id = $this->ctx->user_id;
}
}
if (!is_null($this->ctx->owner_id)) {
if ((!is_numeric($content->owner_id) || is_null($content->owner_id)) && in_array('owner_id', $content::createProperties)) {
$content->owner_id = $this->ctx->owner_id;
}
}
$id = $content->getId();
$toremove = $content->getRemoveOnSet();
if (!empty($toremove)) {
foreach($toremove as $name) {
unset($content->{$name});
}
}
if (!$id) {
$this->ctx->url = $this::api_version .'/' . $this::type;
$this->ctx->method = 'post';
} else {
$this->ctx->url = $this::api_version .'/' . $this::type . '/' . $id;
$this->ctx->method = 'put';
}
$this->ctx->body = $content->toJson();
return new $this->className($this->ctx->fetch());
}
/**
* [!!!] Update an item in the collection
*
* This should update property of an item. But the upstream API is buggy
* here, so no way to know what UPDATE does.
*
* @param BXObject $content The object to be set.
* @return BXObject|false The item is returned as stored in collection or
* false in case of error
*
* @api
*/
function update (BXObject $content):BXObject|false {
if ($content->isReadonly()) { return false; }
$id = $content->getId();
$toremove = $content->getRemoveOnSet();
if (!empty($toremove)) {
foreach($toremove as $name) {
unset($content->{$name});
}
}
if (!$content->getId()) { return $this->set($content); }
$this->ctx->url = $this::api_version .'/' . $this::type . '/' . $id;
/* API BUG according to documentation it should be "patch" but when
* using "patch", I get error 404 as when use "post" with partial data
* it update
*/
$this->ctx->method = 'post';
$this->ctx->body = $content->changesToJson();
return new $this->className($this->ctx->fetch());
}
}
trait tBexioArchiveable {
function archive (BXObject $content):bool {
if ($content->isReadonly()) { return false; }
if (!$content->getId()) { return false; }
$this->ctx->url = $this::api_version .'/' . $this::type . '/' . $content->getId() . '/archive';
$this->ctx->method = 'post';
return $this->ctx->fetch()->success;
}
function unarchive (BXObject $content):bool {
if ($content->isReadonly()) { return false; }
if (!$content->getId()) { return false; }
$this->ctx->url = $this::api_version .'/' . $this::type . '/' . $content->getId() . '/reactivate';
$this->ctx->method = 'post';
return $this->ctx->fetch()->success;
}
}
trait tBexioNumberObject {
function getByNumber (Int|String $id):BXObject {
$this->ctx->url = $this::api_version . '/' . $this::type . '/search';
$this->ctx->method = 'post';
$this->ctx->body = json_encode([[
'field' => $this::NR,
'value' => strval($id),
'criteria' => '='
]]);
return new $this->className($this->ctx->fetch()[0]);
}
}
trait tBexioPDFObject {
function getPDF(Int|BXObject $id):BXObject {
if ($id instanceof BXObject) {
$id = $id->getId();
}
$this->ctx->url = $this::api_version . '/' . $this::type . '/' . strval($id) . '/pdf';
return new \BizCuit\BXObject\PDF($this->ctx->fetch());
}
}
trait tBexioProjectObject {
function listByProject (Int|BXObject $projectId): Array {
if ($projectId instanceof BXObject) {
$projectId = $projectId->getId();
}
$results = [];
$offset = 0;
$count = 500;
do {
$list = $this->list($offset, $count);
$results = array_merge(
$results,
array_map(
fn($e) => new $this->className($e),
array_filter($list, fn($e) => intval($e->project_id) === intval($projectId))
)
);
$offset += $count;
} while (count($list) === $count);
return $results;
}
}
/**
* Represent the enpoint Countries
*
* @link https://docs.bexio.com/#tag/Countries
* @api
*/
class BexioCountry extends BexioAPI {
const type = 'country';
protected string $className = 'BizCuit\BXObject\Country';
protected string $query = 'BizCuit\BXQuery\Country';
use tBexioV2Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint Quotes
*
* @link https://docs.bexio.com/#tag/Quotes
* @api
*/
class BexioQuote extends BexioAPI {
const type = 'kb_offer';
protected string $className = 'BizCuit\BXObject\Quote';
protected string $query = 'BizCuit\BXQuery\Quote';
use tBexioV2Api, tBexioObject, tBexioPDFObject, tBexioProjectObject, tBexioCollection, tBexioNumberObject;
}
/**
* Represent the enpoint Invoices
*
* @link https://docs.bexio.com/#tag/Invoices
* @api
*/
class BexioInvoice extends BexioAPI {
const type = 'kb_invoice';
protected string $className = 'BizCuit\BXObject\Invoice';
protected string $query = 'BizCuit\BXQuery\Invoice';
use tBexioV2Api, tBexioObject, tBexioPDFObject, tBexioProjectObject, tBexioCollection, tBexioNumberObject;
}
/**
* Represent the enpoint Orders
*
* @link https://docs.bexio.com/#tag/Orders
* @api
*/
class BexioOrder extends BexioAPI {
const type = 'kb_order';
protected string $className = 'BizCuit\BXObject\Order';
protected string $query = 'BizCuit\BXQuery\Order';
use tBexioV2Api, tBexioObject, tBexioPDFObject, tBexioProjectObject, tBexioCollection, tBexioNumberObject;
}
/**
* Represent the enpoint Contacts
*
* @link https://docs.bexio.com/#tag/Contacts
* @api
*/
class BexioContact extends BexioAPI {
const type = 'contact';
protected string $className = 'BizCuit\BXObject\Contact';
protected string $query = 'BizCuit\BXQuery\Contact';
use tBexioV2Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint Projects
*
* @link https://docs.bexio.com/#tag/Projects
* @api
*/
class BexioProject extends BexioAPI {
const type = 'pr_project';
protected string $className = 'BizCuit\BXObject\Project';
protected string $query = 'BizCuit\BXQuery\Project';
use tBexioV2Api, tBexioObject, tBexioCollection, tBexioNumberObject, tBexioArchiveable;
}
/**
* Represent the enpoint Contact Relations
*
* @link https://docs.bexio.com/#tag/Contact-Relations
* @api
*/
class BexioContactRelation extends BexioAPI {
const type = 'contact_relation';
protected string $className = 'BizCuit\BXObject\ContactRelation';
protected string $query = 'BizCuit\BXQuery\ContactRelation';
use tBexioV2Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint Additional Addresses
*
* @link https://docs.bexio.com/#tag/Additional-Addresses
* @api
*/
class BexioAdditionalAddress extends BexioAPI {
const type = 'additional_address';
protected string $className = 'BizCuit\BXObject\AdditionalAddress';
protected string $query = 'BizCuit\BXQuery\AdditionalAddress';
use tBexioV2Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint Notes
*
* @link https://docs.bexio.com/#tag/Notes
* @api
*/
class BexioNote extends BexioAPI {
const type = 'note';
protected string $className = 'BizCuit\BXObject\Note';
protected string $query = 'BizCuit\BXQuery\Note';
use tBexioV2Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint User Management
*
* @todo Add fictionnal user management
* @link https://docs.bexio.com/#tag/User-Management
* @api
*/
class BexioUser extends BexioAPI {
const type = 'users';
protected string $className = 'BizCuit\BXObject\User';
protected string $query = 'BizCuit\BXQuery\User';
use tBexioV3Api, tBexioObject, tBexioCollection;
}
/**
* Represent the enpoint Business Activities [read only]
*
* @link https://docs.bexio.com/#tag/Business-Activities
* @api
*/
class BexioBusinessActivity extends BexioAPI {
const type = 'client_service';
protected string $className = 'BizCuit\BXObject\ClientService';
protected string $query = 'BizCuit\BXQuery\ClientService';
use tBexioV2Api, tBexioObject, tBexioCollection;
}