106 public const OS_WINDOWS =
"win";
107 public const OS_IOS =
"ios";
108 public const OS_MACOS =
"mac";
109 public const OS_ANDROID =
"android";
110 public const OS_LINUX =
"linux";
111 public const OS_BSD =
"bsd";
112 public const OS_UNKNOWN =
"other";
114 private static ?
string $os =
null;
115 private static ?UuidInterface $serverUniqueId =
null;
116 private static ?
int $cpuCores =
null;
125 $func = new \ReflectionFunction($closure);
126 if(!str_contains($func->getName(),
'{closure')){
130 $scope = $func->getClosureScopeClass();
134 ($func->getClosureThis() !== null ?
"->" :
"::") .
139 return $func->getName();
141 $filename = $func->getFileName();
143 return "closure@" . ($filename !==
false ?
144 Filesystem::cleanPath($filename) .
"#L" . $func->getStartLine() :
155 $reflect = new \ReflectionClass($obj);
156 if($reflect->isAnonymous()){
157 $filename = $reflect->getFileName();
159 return
"anonymous@" . ($filename !== false ?
160 Filesystem::cleanPath($filename) .
"#L" . $reflect->getStartLine() :
165 return $reflect->getName();
173 return static function(object $o){
189 return array_map(fn(object $o) => clone $o, $array);
201 if(self::$serverUniqueId !== null && $extra ===
""){
202 return self::$serverUniqueId;
205 $machine = php_uname(
"a");
206 $cpuinfo = @file(
"/proc/cpuinfo");
207 if($cpuinfo !==
false){
208 $cpuinfoLines = preg_grep(
"/(model name|Processor|Serial)/", $cpuinfo);
209 if($cpuinfoLines ===
false){
212 $machine .= implode(
"", $cpuinfoLines);
214 $machine .= sys_get_temp_dir();
216 $os = Utils::getOS();
217 if($os === Utils::OS_WINDOWS){
218 @exec(
"ipconfig /ALL", $mac);
219 $mac = implode(
"\n", $mac);
220 if(preg_match_all(
"#Physical Address[. ]{1,}: ([0-9A-F\\-]{17})#", $mac, $matches) > 0){
221 foreach($matches[1] as $i => $v){
222 if($v ===
"00-00-00-00-00-00"){
223 unset($matches[1][$i]);
226 $machine .= implode(
" ", $matches[1]);
228 }elseif($os === Utils::OS_LINUX){
229 if(file_exists(
"/etc/machine-id")){
230 $machine .= file_get_contents(
"/etc/machine-id");
232 @exec(
"ifconfig 2>/dev/null", $mac);
233 $mac = implode(
"\n", $mac);
234 if(preg_match_all(
"#HWaddr[ \t]{1,}([0-9a-f:]{17})#", $mac, $matches) > 0){
235 foreach($matches[1] as $i => $v){
236 if($v ===
"00:00:00:00:00:00"){
237 unset($matches[1][$i]);
240 $machine .= implode(
" ", $matches[1]);
243 }elseif($os === Utils::OS_ANDROID){
244 $machine .= @file_get_contents(
"/system/build.prop");
245 }elseif($os === Utils::OS_MACOS){
246 $machine .= shell_exec(
"system_profiler SPHardwareDataType | grep UUID");
248 $data = $machine . PHP_MAXPATHLEN;
249 $data .= PHP_INT_MAX;
250 $data .= PHP_INT_SIZE;
251 $data .= get_current_user();
252 foreach(get_loaded_extensions() as $ext){
253 $data .= $ext .
":" . phpversion($ext);
257 $uuid = Uuid::uuid3(Uuid::NIL, $data);
260 self::$serverUniqueId = $uuid;
276 public static function getOS(
bool $recalculate =
false) : string{
277 if(self::$os === null || $recalculate){
278 $uname = php_uname(
"s");
279 if(stripos($uname,
"Darwin") !==
false){
280 if(str_starts_with(php_uname(
"m"),
"iP")){
281 self::$os = self::OS_IOS;
283 self::$os = self::OS_MACOS;
285 }elseif(stripos($uname,
"Win") !==
false || $uname ===
"Msys"){
286 self::$os = self::OS_WINDOWS;
287 }elseif(stripos($uname,
"Linux") !==
false){
288 if(@file_exists(
"/system/build.prop")){
289 self::$os = self::OS_ANDROID;
291 self::$os = self::OS_LINUX;
293 }elseif(stripos($uname,
"BSD") !==
false || $uname ===
"DragonFly"){
294 self::$os = self::OS_BSD;
296 self::$os = self::OS_UNKNOWN;
303 public static function getCoreCount(
bool $recalculate =
false) : int{
304 if(self::$cpuCores !== null && !$recalculate){
305 return self::$cpuCores;
309 switch(Utils::getOS()){
310 case Utils::OS_LINUX:
311 case Utils::OS_ANDROID:
312 if(($cpuinfo = @file(
'/proc/cpuinfo')) !==
false){
313 foreach($cpuinfo as $l){
314 if(preg_match(
'/^processor[ \t]*:[ \t]*[0-9]+$/m', $l) > 0){
318 }elseif(($cpuPresent = @file_get_contents(
"/sys/devices/system/cpu/present")) !==
false){
319 if(preg_match(
"/^([0-9]+)\\-([0-9]+)$/", trim($cpuPresent), $matches) > 0){
320 $processors = ((int) $matches[2]) - ((
int) $matches[1]);
325 case Utils::OS_MACOS:
326 $processors = (int) shell_exec(
"sysctl -n hw.ncpu");
328 case Utils::OS_WINDOWS:
329 $processors = (int) getenv(
"NUMBER_OF_PROCESSORS");
332 return self::$cpuCores = $processors;
338 public static function hexdump(
string $bin) : string{
340 $bin = str_split($bin, 16);
341 foreach($bin as $counter => $line){
342 $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32,
" ", STR_PAD_RIGHT), 2,
" "), 24,
" ");
343 $ascii = preg_replace(
'#([^\x20-\x7E])#',
".", $line);
344 $output .= str_pad(dechex($counter << 4), 4,
"0", STR_PAD_LEFT) .
" " . $hex .
" " . $ascii . PHP_EOL;
354 if(!is_string($str)){
355 return gettype($str);
358 return preg_replace(
'#([^\x20-\x7E])#',
'.', $str);
361 public static function javaStringHash(
string $string) : int{
363 for($i = 0, $len = strlen($string); $i < $len; $i++){
364 $ord = ord($string[$i]);
365 if(($ord & 0x80) !== 0){
368 $hash = 31 * $hash + $ord;
374 public static function getReferenceCount(
object $value,
bool $includeCurrent =
true) : int{
376 debug_zval_dump($value);
377 $contents = ob_get_contents();
378 if($contents ===
false)
throw new AssumptionFailedError(
"ob_get_contents() should never return false here");
379 $ret = explode(
"\n", $contents);
382 if(preg_match(
'/^.* refcount\\(([0-9]+)\\)\\{$/', trim($ret[0]), $m) > 0){
383 return ((
int) $m[1]) - ($includeCurrent ? 3 : 4);
388 private static function printableExceptionMessage(\Throwable $e) : string{
389 $errstr = preg_replace(
'/\s+/',
' ', trim($e->getMessage()));
391 $errno = $e->getCode();
394 $errno = ErrorTypeToStringMap::get($errno);
395 }
catch(\InvalidArgumentException $ex){
400 $errfile = Filesystem::cleanPath($e->getFile());
401 $errline = $e->getLine();
403 return get_class($e) .
": \"$errstr\" ($errno) in \"$errfile\" at line $errline";
413 $trace = $e->getTrace();
416 $lines = [self::printableExceptionMessage($e)];
417 $lines[] =
"--- Stack trace ---";
418 foreach(Utils::printableTrace($trace) as $line){
419 $lines[] =
" " . $line;
421 for($prev = $e->getPrevious(); $prev !==
null; $prev = $prev->getPrevious()){
422 $lines[] =
"--- Previous ---";
423 $lines[] = self::printableExceptionMessage($prev);
424 foreach(Utils::printableTrace($prev->getTrace()) as $line){
425 $lines[] =
" " . $line;
428 $lines[] =
"--- End of exception information ---";
432 private static function stringifyValueForTrace(mixed $value,
int $maxStringLength) : string{
434 is_object($value) =>
"object " . self::getNiceClassName($value) .
"#" . spl_object_id($value),
435 is_array($value) =>
"array[" . count($value) .
"]",
436 is_string($value) =>
"string[" . strlen($value) .
"] " . substr(Utils::printable($value), 0, $maxStringLength),
437 is_bool($value) => $value ?
"true" :
"false",
438 is_int($value) =>
"int " . $value,
439 is_float($value) =>
"float " . $value,
440 $value ===
null =>
"null",
441 default => gettype($value) .
" " . Utils::printable((
string) $value)
452 public static function printableTrace(array $trace,
int $maxStringLength = 80) : array{
454 for($i = 0; isset($trace[$i]); ++$i){
456 if(isset($trace[$i][
"args"]) || isset($trace[$i][
"params"])){
457 if(isset($trace[$i][
"args"])){
458 $args = $trace[$i][
"args"];
460 $args = $trace[$i][
"params"];
466 foreach($args as $argId => $value){
467 $paramsList[] = ($argId === $offset ?
"" :
"$argId: ") . self::stringifyValueForTrace($value, $maxStringLength);
470 $params = implode(
", ", $paramsList);
472 $messages[] =
"#$i " .
473 (isset($trace[$i][
"file"]) ? Filesystem::cleanPath($trace[$i][
"file"]) :
"") .
474 "(" . (isset($trace[$i][
"line"]) ? $trace[$i][
"line"] :
"") .
"): " .
475 (isset($trace[$i][
"class"]) ?
476 $trace[$i][
"class"] . (($trace[$i][
"type"] ===
"dynamic" || $trace[$i][
"type"] ===
"->") ?
"->" :
"::") :
479 $trace[$i][
"function"] .
480 "(" . Utils::printable($params) .
")";
495 $printableTrace = self::printableTrace($rawTrace, $maxStringLength);
497 foreach($printableTrace as $frameId => $printableFrame){
498 $rawFrame = $rawTrace[$frameId];
501 $rawFrame[
"file"] ??
null,
502 $rawFrame[
"line"] ?? 0
515 if(function_exists(
"xdebug_get_function_stack") && count($trace = @xdebug_get_function_stack()) !== 0){
516 $trace = array_reverse($trace);
518 $e = new \Exception();
519 $trace = $e->getTrace();
521 for($i = 0; $i < $skipFrames; ++$i){
524 return array_values($trace);
531 return self::printableTrace(self::currentTrace(++$skipFrames));
540 $rawDocComment = substr($docComment, 3, -2);
541 preg_match_all(
'/(*ANYCRLF)^[\t ]*(?:\* )?@([a-zA-Z\-]+)(?:[\t ]+(.+?))?[\t ]*$/m', $rawDocComment, $matches);
543 return array_combine($matches[1], $matches[2]);
551 $baseInterface = false;
552 if(!class_exists($baseName)){
553 if(!interface_exists($baseName)){
554 throw new \InvalidArgumentException(
"Base class $baseName does not exist");
556 $baseInterface =
true;
558 if(!class_exists($className)){
559 throw new \InvalidArgumentException(
"Class $className does not exist or is not a class");
561 if(!is_a($className, $baseName,
true)){
562 throw new \InvalidArgumentException(
"Class $className does not " . ($baseInterface ?
"implement" :
"extend") .
" $baseName");
564 $class = new \ReflectionClass($className);
565 if(!$class->isInstantiable()){
566 throw new \InvalidArgumentException(
"Class $className cannot be constructed");
584 $signature = CallbackType::createFromCallable($signature);
586 if(!$signature->isSatisfiedBy($subject)){
587 throw new \TypeError(
"Declaration of callable `" . CallbackType::createFromCallable($subject) .
"` must be compatible with `" . $signature .
"`");
597 foreach($array as $k => $v){
600 }
catch(\TypeError $e){
601 throw new \TypeError(
"Incorrect type of element at \"$k\": " . $e->getMessage(), 0, $e);
617 foreach($array as $key => $value){
618 yield (
string) $key => $value;
634 public static function checkUTF8(
string $string) : void{
635 if(!mb_check_encoding($string,
'UTF-8')){
636 throw new \InvalidArgumentException(
"Text must be valid UTF-8");
646 public static function assumeNotFalse(mixed $value, \Closure|
string $context =
"This should never be false") : mixed{
647 if($value === false){
648 throw new AssumptionFailedError(
"Assumption failure: " . (is_string($context) ? $context : $context()) .
" (THIS IS A BUG)");
653 public static function checkFloatNotInfOrNaN(
string $name,
float $float) : void{
655 throw new \InvalidArgumentException(
"$name cannot be NaN");
657 if(is_infinite($float)){
658 throw new \InvalidArgumentException(
"$name cannot be infinite");
662 public static function checkVector3NotInfOrNaN(Vector3 $vector3) : void{
663 if($vector3 instanceof Location){
664 self::checkFloatNotInfOrNaN(
"yaw", $vector3->yaw);
665 self::checkFloatNotInfOrNaN(
"pitch", $vector3->pitch);
667 self::checkFloatNotInfOrNaN(
"x", $vector3->x);
668 self::checkFloatNotInfOrNaN(
"y", $vector3->y);
669 self::checkFloatNotInfOrNaN(
"z", $vector3->z);
672 public static function checkLocationNotInfOrNaN(Location $location) : void{
673 self::checkVector3NotInfOrNaN($location);
682 function_exists(
'opcache_get_status') &&
683 ($opcacheStatus = opcache_get_status(false)) !== false &&
684 isset($opcacheStatus[
"jit"][
"on"])
686 $jit = $opcacheStatus[
"jit"];
687 if($jit[
"on"] ===
true){
688 return (($jit[
"opt_flags"] >> 2) * 1000) +
689 (($jit[
"opt_flags"] & 0x03) * 100) +
690 ($jit[
"kind"] * 10) +
707 return mt_rand() / mt_getrandmax();