-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathkphp_polyfills.php
1580 lines (1313 loc) · 44.3 KB
/
kphp_polyfills.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
// Compiler for PHP (aka KPHP) polyfills
// Copyright (c) 2020 LLC «V Kontakte»
// Distributed under the GPL v3 License, see LICENSE.notice.txt
/** @noinspection PhpUnused */
/** @noinspection PhpUnusedParameterInspection */
/** @noinspection PhpComposerExtensionStubsInspection */
/** @noinspection PhpDocSignatureInspection */
/** @noinspection PhpDocMissingReturnTagInspection */
/** @noinspection PhpUnhandledExceptionInspection */
/** @noinspection KphpDocInspection */
/** @noinspection NoTypeDeclarationInspection */
/** @noinspection KphpReturnTypeMismatchInspection */
/** @noinspection KphpParameterTypeMismatchInspection */
/*
* This file contains implemetation of KPHP native functions written in plain PHP.
* So, while executing a script in plain PHP - this implementation is used,
* but after compilation they are replaced by built-in ones.
*
* (Some KPHP functions can't be expressed in PHP - they are written with C, see vkext.helper.php)
*/
#ifndef KPHP // all contents of this file is invisible for KPHP
#region constants
define('KPHP_COMPILER_VERSION', '');
#endregion
#region types
// functions that are KPHP keywords, related to type system
/**
* tuple(T1, T2, ...) - compile-time sized, read-only "array" with compile-time known indexing access
* In plain PHP it is just an array of input arguments: tuple(1,'s') === [1,'s']
* In KPHP types are tracked separately
* @noinspection PhpDocSignatureInspection
* @noinspection PhpUnusedParameterInspection
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function tuple(...$args) {
// turn off PhpStorm native inferring
return ${'args'};
}
/**
* shape(['k1' => T1, 'k2' => T2, ...]) - like tuple, but with named arguments
* In plain PHP it is just an associative array, the same as provided argument
* In KPHP types are tracked separately, there is no hashtable (and even strings) at runtime
* @noinspection PhpDocSignatureInspection
* @noinspection PhpUnusedParameterInspection
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function shape(array $associative_arr) {
// turn off PhpStorm native inferring
return ${'associative_arr'};
}
/**
* not_null(?T) : T
* @param any $any_value
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function not_null($any_value) {
if ($any_value === null) {
warning("Passed 'null' to not_null() in PHP");
}
// turn off PhpStorm native inferring
return ${'any_value'};
}
/**
* not_false(T|false) : T
* @param any $any_value
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function not_false($any_value) {
if ($any_value === false) {
warning("Passed 'false' to not_false() in PHP");
}
// turn off PhpStorm native inferring
return ${'any_value'};
}
#endregion
#region instance cache
// in KPHP, instances are cached for $ttl across requests in shared memory
// in PHP, just use globals for current request - not effective, but polyfill logic remains the same
global $kphp_fake_instance_cache;
$kphp_fake_instance_cache = [];
/**
* instance_cache_fetch(SomeClass::class, 'key') : SomeClass
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function instance_cache_fetch(string $type, string $key) {
global $kphp_fake_instance_cache;
if (isset($kphp_fake_instance_cache[$key]) && $kphp_fake_instance_cache[$key] instanceof $type) {
return $kphp_fake_instance_cache[$key];
}
return null;
}
/**
* @param object $value Any instance
* @param int $ttl In seconds (ignored in php)
*/
function instance_cache_store(string $key, $value, $ttl = -1): bool {
global $kphp_fake_instance_cache;
$kphp_fake_instance_cache[$key] = clone $value;
return true;
}
function instance_cache_update_ttl(string $key, int $ttl = 0): bool {
// no ttl in php polyfill
global $kphp_fake_instance_cache;
return isset($kphp_fake_instance_cache[$key]);
}
function instance_cache_delete(string $key): bool {
global $kphp_fake_instance_cache;
$deleted = isset($kphp_fake_instance_cache[$key]);
unset($kphp_fake_instance_cache[$key]);
return $deleted;
}
#endregion
#region instances
// casting instances to different types
/**
* instance_cast($any_object, SomeClass::class) : SomeClass
* @param object $instance Any non-null instance - known to be of type SomeClass, but can't be inferred
* @param string $class_name Compile-time constant
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function instance_cast(?object $instance, string $class_name) {
if ($instance === null) {
return null;
}
if (!($instance instanceof $class_name)) {
return null;
}
return $instance; // it just returns the argument, but KPHP infers it as SomeClass
}
/**
* to_array_debug($any_object) : mixed[] - deep convertation to object to array
* Similar to (array)$any_object, but deep and with strict behaviour.
* Useful for logging and debugging.
* For all classes that are array-converted, KPHP generates an effective C++ visitor.
* @param bool $with_class_names Should the resulting array contain class names
* @param bool $public_members_only Should the resulting array contain only public fields
* @return mixed[]
*/
function to_array_debug($any, $with_class_names = false, $public_members_only = false) {
// (array) $instance in PHP outputs private/protected fields as '\0ClassName\0fieldName'
// kphp omit such control characters
$isPrivateField = function($key) { return $key[0] === "\0"; };
$demangleField = function($key) use ($isPrivateField) {
if ($isPrivateField($key)) {
$key = preg_replace("/\\0.+\\0/", '', $key);
}
return $key;
};
$toArray = function($v) use (&$toArray, &$demangleField, &$with_class_names, $public_members_only, $isPrivateField) {
if (is_object($v)) {
$result = [];
foreach ((array)$v as $field => $value) {
if ($public_members_only && $isPrivateField($field)) {
continue;
}
$result[$demangleField($field)] = $toArray($value);
}
if ($with_class_names) {
$result['__class_name'] = get_class($v);
}
return $result;
}
if (is_array($v)) {
return array_map($toArray, $v);
}
return $v;
};
if ($any === null) {
return [];
}
return $toArray($any);
}
/**
* @see to_array_debug function
*/
function instance_to_array($instance, $with_class_names = false) {
return to_array_debug($instance, $with_class_names);
}
/**
* classof($obj) is a KPHP construct to express some logic in generics, like
* `instance_cast($arg, classof($obj))`
* In KPHP, it works at compile-time, no such runtime function exists.
* In PHP, it just returns get_class(), here we can't do it better, though it's not generally true, use with care.
*/
function classof(object $obj): string {
return get_class($obj);
}
class JsonEncoder {
// these constants can be overridden in child classes
const rename_policy = 'none';
const visibility_policy = 'all';
const skip_if_default = false;
const float_precision = 0;
private function __construct() { }
public static function encode(?object $instance, int $flags = 0, array $more = []): string {
if ($instance === null) {
return 'null';
}
try {
self::$lastError = '';
$serializer = new KPHP\JsonSerialization\JsonSerializer($instance, get_class($instance), static::class);
return $serializer->serializeInstanceToJson($flags, $more);
} catch (Throwable $e) {
self::$lastError = $e->getMessage();
return '';
}
}
public static function decode(string $json_string, string $class_name): ?object {
try {
self::$lastError = '';
$deserializer = new KPHP\JsonSerialization\JsonDeserializer($class_name, static::class);
return $deserializer->unserializeInstanceFromJson($json_string);
} catch (\JsonException $ex) {
self::$lastError = $json_string === '' ? 'provided empty json string' : 'failed to parse json string: ' . $ex->getMessage();
return null;
} catch (Throwable $ex) {
self::$lastError = $ex->getMessage();
return null;
}
}
public static function getLastError(): string {
return self::$lastError;
}
private static string $lastError = '';
}
#endregion
#region resumable
// resumable functions - forks - are close to coroutines (green threads); in PHP they remain synchronous
global $__forked;
$__forked = [];
/**
* fork(f(...$args)) : future<ReturnT(f)> (int in PHP)
* @param any $x
*/
function fork($x) {
global $__forked;
$__forked[] = $x;
return count($__forked);
}
function _php_wait_helper($id) {
global $__forked;
$cnt = is_array($__forked) ? count($__forked) : 0;
return 0 < $id && $id <= $cnt && $__forked[$id - 1] !== '__already_gotten__';
}
function wait($id, $timeout = -1.0) {
global $__forked;
if (!_php_wait_helper($id)) {
return null;
}
$result = $__forked[$id - 1];
$__forked[$id - 1] = '__already_gotten__';
return $result;
}
function wait_multi($futures) {
$result = [];
foreach ($futures as $key => $future) {
$result[$key] = wait($future);
}
return $result;
}
function wait_synchronously($id) {
return wait($id);
}
function wait_concurrently($id) {
static $waiting = [];
if (!$waiting[$id]) {
$waiting[$id] = true;
_php_wait_helper($id);
unset($waiting[$id]);
} else {
while ($waiting[$id]) {
sched_yield();
if ($waiting[$id]) {
usleep(10 * 1000);
}
}
}
}
function wait_queue_create(array $futures): array {
return $futures;
}
function wait_queue_push(&$future_queue, $future) {
assert(is_array($future_queue)); // array in php, future_queue<T> in kphp
assert($future >= 0); // int in php, future<T> in kphp
$future_queue[] = $future;
}
function wait_queue_empty($future_queue) {
assert(is_array($future_queue));
return count($future_queue) === 0;
}
function wait_queue_next(&$future_queue, $timeout = -1.0) {
if (wait_queue_empty($future_queue)) {
return 0;
}
return array_shift($future_queue);
}
function wait_queue_next_synchronously(&$future_queue) {
return wait_queue_next($future_queue, -1);
}
function sched_yield() {
}
/**
* @param float $timeout in seconds
*/
function sched_yield_sleep($timeout) {
}
function rpc_tl_query_result_synchronously($query_ids) {
return rpc_tl_query_result($query_ids);
}
function rpc_get_synchronously($qid) {
return rpc_get($qid);
}
/**
* KphpRpcRequestsExtraInfo is a built-in kPHP class. Its instances could be passed
* into [typed_]rpc_tl_query function. 'get' method returns extra info for all queries
* processed in a call to [typed_]rpc_tl_query function.
*/
final class KphpRpcRequestsExtraInfo {
/**
* @return tuple(int)[]
*/
public function get(): array {
return [];
}
}
/**
* @param int $resumable_id
* @return ?tuple(int, float)
*/
function extract_kphp_rpc_response_extra_info($resumable_id) {
return null;
}
/**
* @param int[] $query_ids
* @return array
*/
function typed_rpc_tl_query_result_synchronously(array $query_ids) {
return typed_rpc_tl_query_result($query_ids);
}
function get_running_fork_id(): int {
return 0;
}
/**
* @return string|false
*/
function curl_exec_concurrently($curl_handle, float $timeout_sec = 1.0) {
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
if ($timeout_sec > 0) {
curl_setopt($curl_handle, CURLOPT_TIMEOUT_MS, (int)($timeout_sec * 1000));
}
return curl_exec($curl_handle);
}
#endregion
#region arrays
// array_* functions that are missing in PHP or made for better type inferring
/**
* @return int|string|null
*/
function array_first_key(array $a) {
reset($a);
return key($a);
}
/**
* array_first_value(T[]) : T
*
* Note that the result can differ between PHP and KPHP for an empty array:
* * In PHP the function returns `null` regardless the array type, so actual return type is `?T`.
* * In KPHP the function always returns result of type `T`.
*
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function array_first_value(array $a) {
return $a ? reset($a) : null;
}
/**
* @return int|string|null
*/
function array_last_key(array $a) {
end($a);
return key($a);
}
/**
* array_last_value(T[]) : T
*
* Note that the result can differ between PHP and KPHP for an empty array:
* * In PHP the function returns `null` regardless the array type, so actual return type is `?T`.
* * In KPHP the function always returns result of type `T`.
*
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function array_last_value(array $a) {
return $a ? end($a) : null;
}
/**
* Swap two items in an array.
* Done efficiently in KPHP, especially for vectors.
*/
function array_swap_int_keys(array &$a, int $idx1, int $idx2): void {
if ($idx1 != $idx2 && isset($a[$idx1]) && isset($a[$idx2])) {
$tmp = $a[$idx1];
$a[$idx1] = $a[$idx2];
$a[$idx2] = $tmp;
}
}
/**
* @return string[]
*/
function array_keys_as_strings(array $a) {
$keys = [];
foreach ($a as $key => $_) {
$keys[] = (string)$key;
}
return $keys;
}
/**
* @return int[]
*/
function array_keys_as_ints(array $a) {
$keys = [];
foreach ($a as $key => $_) {
$keys[] = (int)$key;
}
return $keys;
}
/**
*/
function array_merge_into(array &$a, array $another_array) {
$a = array_merge($a, $another_array);
}
/**
* array_find(T[], fn) : tuple(key, T)
* @return tuple(int|string|null, any)
*/
function array_find(array $ar, callable $clbk) {
foreach ($ar as $k => $v) {
if ($clbk($v)) {
return tuple($k, $v);
}
}
return tuple(null, null);
}
/**
* array_filter_by_key(T[], fn) : T[]
* @ return can't be expressed in phpdoc, done via KPHPStorm plugin for IDE
*/
function array_filter_by_key(array $array, callable $callback) {
return array_filter($array, $callback, ARRAY_FILTER_USE_KEY);
}
/**
* A useful function to reserve array memory - if you know in advance, how much elements will be inserted to it.
* Effective especially for vectors, as there will be no reallocation on insertion.
*
* Note: This is a low level function. For more user-friendly API check following aliases:
* @see array_reserve_vector
* @see array_reserve_map_int_keys
* @see array_reserve_map_string_keys
*
* @param array $arr Target array (vector/map)
* @param int $int_keys_num Amount of int keys
* @param int $str_keys_num Amount of string keys
* @param bool $is_vector Should it be a vector (if string keys amount is 0)
*/
function array_reserve(&$arr, $int_keys_num, $str_keys_num, $is_vector) {
// in PHP does nothing
}
/**
* More useful @see array_reserve() alias for map with string keys.
* Similar to calling: array_reserve($arr, $capacity, 0, true).
*
* @param array $arr Target array (vector/map)
* @param int $capacity Amount of the elements (for vector) or int keys (for map with int keys)
*/
function array_reserve_vector(&$arr, $capacity) {
// in PHP does nothing
}
/**
* More useful @see array_reserve() alias for map with int keys.
* Similar to calling: array_reserve($arr, $capacity, 0, false).
*
* @param array $arr Target array (vector/map)
* @param int $int_keys_num Amount of int keys
*/
function array_reserve_map_int_keys(&$arr, $int_keys_num) {
// in PHP does nothing
}
/**
* More useful @see array_reserve() alias for map with string keys.
* Similar to calling: array_reserve($arr, 0, $capacity, false).
*
* @param array $arr Target array (vector/map)
* @param int $str_keys_num Amount of string keys
*/
function array_reserve_map_string_keys(&$arr, $str_keys_num) {
// in PHP does nothing
}
/**
* The same as @see array_reserve(), but takes all sizes (length, key type, is vector) from array $base.
*
* @param array $arr Target array (vector/map)
* @param array $base Source of array size
*/
function array_reserve_from(array &$arr, array $base) {
// in PHP does nothing
}
/**
* Checks whether an array is internally a vector (a contiguous chunk of memory
* with integer keys from 0 to length-1) in KPHP.
* Always returns false in PHP because we don't know the internals of PHP.
*
* Since PHP8, there is the `array_is_list()` function, but it's not exactly what this function returns in KPHP.
*/
function array_is_vector(array $arr): bool {
return false;
}
/**
* array_unset(T[], $key) : T - unset value in array and return it
*/
function array_unset(array &$arr, $key) {
$res = $arr[$key];
unset($arr[$key]);
return $res;
}
/**
* @deprecated
* @param array $a
* @param int $n
* @return array [key, value]
*/
function _php_getElementByPos_helper($a, $n) {
// return is_array($a) ? each(array_slice($a, $n, 1)) : array();
if (!is_array($a)) {
return [];
}
$l = count($a);
if ($n < -$l / 2) {
$n += $l;
if ($n < 0) {
return [];
}
}
if ($n > $l / 2) {
$n -= $l;
if ($n >= 0) {
return [];
}
}
if ($n < 0) {
end($a);
$n++;
while ($n < 0) {
$n++;
prev($a);
}
} else {
reset($a);
while ($n > 0) {
$n--;
next($a);
}
}
// replacement of deprecated each() function
$result = [
1 => current($a),
'value' => current($a),
0 => key($a),
'key' => key($a),
];
next($a);
return $result;
}
/**
* @deprecated
* @see array_first_key(), array_last_key()
* @param array $a
* @param int $n
* @return any
*/
function getKeyByPos($a, $n) {
$element = _php_getElementByPos_helper($a, $n);
return $element[0];
}
/**
* @deprecated
* @see array_first_value(), array_last_value()
* @param array $a
* @param int $n
* @return any
*/
function getValueByPos($a, $n) {
$element = _php_getElementByPos_helper($a, $n);
return $element[1];
}
/**
* create_vector($n, $x) : typeof($x)[] (vector-array of size n)
* @param int $n
* @param any $x
* @return array
*/
function create_vector($n, $x) {
$res = [];
for ($i = 0; $i < $n; $i++) {
$res[] = $x;
}
return $res;
}
#endregion
#region serialization
// serialize instances and vars to binary msgpack representation (and back)
/** @return any */
function _php_serialize_helper_run_or_warning(callable $fun) {
try {
return $fun();
} catch (Throwable $e) {
warning($e->getMessage() . "\n" . $e->getTraceAsString());
return null;
}
}
function instance_serialize(object $instance): ?string {
KPHP\MsgPackSerialization\ClassTransformer::$depth = 0;
return _php_serialize_helper_run_or_warning(static function() use ($instance) {
$packer = (new MessagePack\Packer(MessagePack\PackOptions::FORCE_STR))->extendWith(new KPHP\MsgPackSerialization\ClassTransformer());
return $packer->pack($instance);
});
}
function instance_serialize_safe(object $instance): string {
KPHP\MsgPackSerialization\ClassTransformer::$depth = 0;
$packer = (new MessagePack\Packer(MessagePack\PackOptions::FORCE_STR))->extendWith(new KPHP\MsgPackSerialization\ClassTransformer());
return $packer->pack($instance);
}
function instance_deserialize(string $packed_str, string $type_of_instance): ?object {
return _php_serialize_helper_run_or_warning(static function() use ($packed_str, $type_of_instance) {
$unpacked_array = msgpack_deserialize_safe($packed_str);
$instance_parser = new KPHP\MsgPackSerialization\MsgPackDeserializer($type_of_instance);
return $instance_parser->fromUnpackedArray($unpacked_array);
});
}
function instance_deserialize_safe(string $packed_str, string $type_of_instance): ?object {
$unpacked_array = msgpack_deserialize_safe($packed_str);
$instance_parser = new KPHP\MsgPackSerialization\MsgPackDeserializer($type_of_instance);
return $instance_parser->fromUnpackedArray($unpacked_array);
}
/**
* @param mixed $value
*/
function msgpack_serialize($value): ?string {
return _php_serialize_helper_run_or_warning(static function() use ($value) {
return msgpack_serialize_safe($value);
});
}
/**
* @param mixed $value
* @throws MessagePack\Exception\InvalidOptionException
* @throws MessagePack\Exception\PackingFailedException
*/
function msgpack_serialize_safe($value): string {
$packer = new MessagePack\Packer(MessagePack\PackOptions::FORCE_STR);
return $packer->pack($value);
}
/**
* @param string $packed_str
* @return mixed
*/
function msgpack_deserialize(string $packed_str) {
return _php_serialize_helper_run_or_warning(static function() use ($packed_str) {
return msgpack_deserialize_safe($packed_str);
});
}
/**
* @throws MessagePack\Exception\InvalidOptionException
* @throws MessagePack\Exception\UnpackingFailedException
* @return any
*/
function msgpack_deserialize_safe(string $packed_str) {
$unpacker = new MessagePack\BufferUnpacker($packed_str, null);
$result = $unpacker->unpack();
if (($remaining = $unpacker->getRemainingCount())) {
$off = strlen($packed_str) - $remaining;
throw new MessagePack\Exception\UnpackingFailedException("Consumed only first {$off} characters of " . strlen($packed_str) . " during deserialization");
}
return $result;
}
#endregion
#region confdata
// confdata functions can't be polyfilled and therefore must be called only if kphp === 1
function is_confdata_loaded(): bool {
return false;
}
/** @return mixed */
function confdata_get_value(string $key) {
return false;
}
/** @return mixed[] */
function confdata_get_values_by_predefined_wildcard(string $prefix) {
return [];
}
#endregion
#region profiler
// profiler is enabled only in KPHP with env KPHP_PROFILER=1, PHP can't polyfill this
/**
* Is KPHP profiler enabled.
* When disabled, invocations are replaced with 'false' while compilation,
* that's whe if(profiler_is_enabled()) are cut our by gcc, and you can use it even in highload places
*/
function profiler_is_enabled(): bool {
return false;
}
/**
* Tells KPHP profiler to "split" current function.
* As a purpose, instead of just rpcCall() we want to see rpcCall(mc), rpcCall(targ2) and others for engine targets.
* In this case, $label is an actor name.
*/
function profiler_set_function_label(string $label) {
}
/**
* Not obligatory function for KPHP profiler, forcing a given suffix to a profile output filename.
* (by default suffix is a name of @kphp-profile function)
* Ideological usage pattern: call it in special cases somewhere deeply in callstack - to find a wanted file easier.
*/
function profiler_set_log_suffix(string $suffix) {
}
#endregion
#region memory
// getting memory stats from PHP code at production, don't confuse with deep-memory profiling
/**
* An array ["$var_name" => size_in_bytes].
* Works only in KPHP, don't use it in production - only to debug, which globals/statics allocate huge pieces of memory.
*
* While compiling, a special env variable should be set to enable this functions:
* KPHP_ENABLE_GLOBAL_VARS_MEMORY_STATS=1 kphp ...
*
* In PHP, does nothing.
* @return int[]
*/
function get_global_vars_memory_stats() {
return [];
}
/**
* Returns currently used and dirty memory (in bytes)
*/
function memory_get_total_usage(): int {
return 0;
}
/**
* Returns heap memory usage (system heap, not script allocator) (in bytes)
*/
function memory_get_static_usage(): int {
return 0;
}
/**
* Returns dictionary with the following stats:
* 'memory_limit' - max memory available (512MB by default)
* 'real_memory_used' - right bound at memory arena
* 'memory_used' - total memory currently used
* 'max_real_memory_used' - max of 'real_memory_used'
* 'max_memory_used' - max of 'memory_used'
* 'defragmentation_calls' - the total number of defragmentation process calls
* 'huge_memory_pieces' - the number of huge memory pirces (in rb tree)
* 'small_memory_pieces' - the number of small memory pieces (in lists)
* 'heap_memory_used' - total heap memory currently used
* @return int[]
*/
function memory_get_detailed_stats() {
return [];
}
/**
* Returns tuple of (allocations_count, allocated_total).
* @return tuple(int, int)
*/
function memory_get_allocations() {
return tuple(0, 0);
}
#endregion
#region job workers
// contains declarations for KPHP job workers api
// it has NO PHP IMPLEMENTATION; kphp_job_worker_start() isn't supposed to be called in plain PHP
/**
* Job workers are separate processes which can be invoked from HTTP workers to parallelize your PHP code.
* Unlike forks, that are coroutines actually, job workers can parallelize CPU-consuming execution.
* @see kphp_job_worker_start accepting \KphpJobWorkerRequest and returning future<\KphpJobWorkerResponse>|false
* @see wait accepting future<T>|false and returning ?T
* To handle job requests in an entrypoint, test for $_SERVER["JOB_ID"]
*/
interface KphpJobWorkerRequest {
}
/**
* Job workers are separate processes which can be invoked from HTTP workers to parallelize your PHP code.
* @see \KphpJobWorkerRequest
*/
interface KphpJobWorkerResponse {
}
/**
* Classes marked with this interface can be shared across multiple job workers (for reading only due to immutability).
* This is used for optimization: it allows copying an object only once while launching multiple job workers.
* Consider the docs for details.
* @see kphp_job_worker_start_multi
* @kphp-immutable-class
*/
interface KphpJobWorkerSharedMemoryPiece {
}
/**
* When a job worker fails, this built-in instance is returned from wait().
* In other words, it's an error result for future<KphpJobWorkerResponse>
* Hence, having called wait(), you should test the result with instanceof, handling an error and probably providing a local execution path.
*/
class KphpJobWorkerResponseError implements KphpJobWorkerResponse {
// Job script execution errors:
const JOB_MEMORY_LIMIT_ERROR = -101;
const JOB_TIMEOUT_ERROR = -102;
const JOB_EXCEPTION_ERROR = -103;
const JOB_STACK_OVERFLOW_ERROR = -104;
const JOB_PHP_ASSERT_ERROR = -105;
const JOB_CLIENT_MEMORY_LIMIT_ERROR = -1001; // client doesn't have enough memory to accept job response
const JOB_NOTHING_REPLIED_ERROR = -2001; // kphp_job_worker_store_response() was not succeeded
const JOB_STORE_RESPONSE_INCORRECT_CALL_ERROR = -3000;
const JOB_STORE_RESPONSE_NOT_ENOUGH_SHARED_MESSAGES_ERROR = -3001;
const JOB_STORE_RESPONSE_TOO_BIG_ERROR = -3002;
const JOB_STORE_RESPONSE_CANT_SEND_ERROR = -3003;
public function getError(): string {
return '';
}
public function getErrorCode(): int {
return 0;
}
}
/**
* Returns whether KPHP is launched with at least one job worker process.
* Your code must be always prepared to provide a local execution path if job workers are turned off on KPHP launch.
*/
function is_kphp_job_workers_enabled(): bool {
return false;