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();
179 return array_map(fn(object $o) => clone $o, $array);
191 if(self::$serverUniqueId !== null && $extra ===
""){
192 return self::$serverUniqueId;
195 $machine = php_uname(
"a");
196 $cpuinfo = @file(
"/proc/cpuinfo");
197 if($cpuinfo !==
false){
198 $cpuinfoLines = preg_grep(
"/(model name|Processor|Serial)/", $cpuinfo);
199 if($cpuinfoLines ===
false){
202 $machine .= implode(
"", $cpuinfoLines);
204 $machine .= sys_get_temp_dir();
206 $os = Utils::getOS();
207 if($os === Utils::OS_WINDOWS){
208 @exec(
"ipconfig /ALL", $mac);
209 $mac = implode(
"\n", $mac);
210 if(preg_match_all(
"#Physical Address[. ]{1,}: ([0-9A-F\\-]{17})#", $mac, $matches) > 0){
211 foreach($matches[1] as $i => $v){
212 if($v ===
"00-00-00-00-00-00"){
213 unset($matches[1][$i]);
216 $machine .= implode(
" ", $matches[1]);
218 }elseif($os === Utils::OS_LINUX){
219 if(file_exists(
"/etc/machine-id")){
220 $machine .= file_get_contents(
"/etc/machine-id");
222 @exec(
"ifconfig 2>/dev/null", $mac);
223 $mac = implode(
"\n", $mac);
224 if(preg_match_all(
"#HWaddr[ \t]{1,}([0-9a-f:]{17})#", $mac, $matches) > 0){
225 foreach($matches[1] as $i => $v){
226 if($v ===
"00:00:00:00:00:00"){
227 unset($matches[1][$i]);
230 $machine .= implode(
" ", $matches[1]);
233 }elseif($os === Utils::OS_ANDROID){
234 $machine .= @file_get_contents(
"/system/build.prop");
235 }elseif($os === Utils::OS_MACOS){
236 $machine .= shell_exec(
"system_profiler SPHardwareDataType | grep UUID");
238 $data = $machine . PHP_MAXPATHLEN;
239 $data .= PHP_INT_MAX;
240 $data .= PHP_INT_SIZE;
241 $data .= get_current_user();
242 foreach(get_loaded_extensions() as $ext){
243 $data .= $ext .
":" . phpversion($ext);
247 $uuid = Uuid::uuid3(Uuid::NIL, $data);
250 self::$serverUniqueId = $uuid;
259 public static function getOS(
bool $recalculate =
false) : string{
260 if(self::$os === null || $recalculate){
261 $uname = php_uname(
"s");
262 if(stripos($uname,
"Darwin") !==
false){
263 if(str_starts_with(php_uname(
"m"),
"iP")){
264 self::$os = self::OS_IOS;
266 self::$os = self::OS_MACOS;
268 }elseif(stripos($uname,
"Win") !==
false || $uname ===
"Msys"){
269 self::$os = self::OS_WINDOWS;
270 }elseif(stripos($uname,
"Linux") !==
false){
271 if(@file_exists(
"/system/build.prop")){
272 self::$os = self::OS_ANDROID;
274 self::$os = self::OS_LINUX;
276 }elseif(stripos($uname,
"BSD") !==
false || $uname ===
"DragonFly"){
277 self::$os = self::OS_BSD;
279 self::$os = self::OS_UNKNOWN;
286 public static function getCoreCount(
bool $recalculate =
false) : int{
287 if(self::$cpuCores !== null && !$recalculate){
288 return self::$cpuCores;
292 switch(Utils::getOS()){
293 case Utils::OS_LINUX:
294 case Utils::OS_ANDROID:
295 if(($cpuinfo = @file(
'/proc/cpuinfo')) !==
false){
296 foreach($cpuinfo as $l){
297 if(preg_match(
'/^processor[ \t]*:[ \t]*[0-9]+$/m', $l) > 0){
301 }elseif(($cpuPresent = @file_get_contents(
"/sys/devices/system/cpu/present")) !==
false){
302 if(preg_match(
"/^([0-9]+)\\-([0-9]+)$/", trim($cpuPresent), $matches) > 0){
303 $processors = ((int) $matches[2]) - ((
int) $matches[1]);
308 case Utils::OS_MACOS:
309 $processors = (int) shell_exec(
"sysctl -n hw.ncpu");
311 case Utils::OS_WINDOWS:
312 $processors = (int) getenv(
"NUMBER_OF_PROCESSORS");
315 return self::$cpuCores = $processors;
321 public static function hexdump(
string $bin) : string{
323 $bin = str_split($bin, 16);
324 foreach($bin as $counter => $line){
325 $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32,
" ", STR_PAD_RIGHT), 2,
" "), 24,
" ");
326 $ascii = preg_replace(
'#([^\x20-\x7E])#',
".", $line);
327 $output .= str_pad(dechex($counter << 4), 4,
"0", STR_PAD_LEFT) .
" " . $hex .
" " . $ascii . PHP_EOL;
337 if(!is_string($str)){
338 return gettype($str);
341 return preg_replace(
'#([^\x20-\x7E])#',
'.', $str);
344 public static function javaStringHash(
string $string) : int{
346 for($i = 0, $len = strlen($string); $i < $len; $i++){
347 $ord = ord($string[$i]);
348 if(($ord & 0x80) !== 0){
351 $hash = 31 * $hash + $ord;
357 public static function getReferenceCount(
object $value,
bool $includeCurrent =
true) : int{
359 debug_zval_dump($value);
360 $contents = ob_get_contents();
361 if($contents ===
false)
throw new AssumptionFailedError(
"ob_get_contents() should never return false here");
362 $ret = explode(
"\n", $contents, limit: 2);
365 if(preg_match(
'/^.* refcount\\(([0-9]+)\\)\\{$/', trim($ret[0]), $m) > 0){
366 return ((
int) $m[1]) - ($includeCurrent ? 3 : 4);
371 private static function printableExceptionMessage(\Throwable $e) : string{
372 $errstr = preg_replace(
'/\s+/',
' ', trim($e->getMessage()));
374 $errno = $e->getCode();
377 $errno = ErrorTypeToStringMap::get($errno);
378 }
catch(\InvalidArgumentException $ex){
383 $errfile = Filesystem::cleanPath($e->getFile());
384 $errline = $e->getLine();
386 return get_class($e) .
": \"$errstr\" ($errno) in \"$errfile\" at line $errline";
396 $trace = $e->getTrace();
399 $lines = [self::printableExceptionMessage($e)];
400 $lines[] =
"--- Stack trace ---";
401 foreach(Utils::printableTrace($trace) as $line){
402 $lines[] =
" " . $line;
404 for($prev = $e->getPrevious(); $prev !==
null; $prev = $prev->getPrevious()){
405 $lines[] =
"--- Previous ---";
406 $lines[] = self::printableExceptionMessage($prev);
407 foreach(Utils::printableTrace($prev->getTrace()) as $line){
408 $lines[] =
" " . $line;
411 $lines[] =
"--- End of exception information ---";
415 private static function stringifyValueForTrace(mixed $value,
int $maxStringLength) : string{
417 is_object($value) =>
"object " . self::getNiceClassName($value) .
"#" . spl_object_id($value),
418 is_array($value) =>
"array[" . count($value) .
"]",
419 is_string($value) =>
"string[" . strlen($value) .
"] " . substr(Utils::printable($value), 0, $maxStringLength),
420 is_bool($value) => $value ?
"true" :
"false",
421 is_int($value) =>
"int " . $value,
422 is_float($value) =>
"float " . $value,
423 $value ===
null =>
"null",
424 default => gettype($value) .
" " . Utils::printable((
string) $value)
435 public static function printableTrace(array $trace,
int $maxStringLength = 80) : array{
437 for($i = 0; isset($trace[$i]); ++$i){
439 if(isset($trace[$i][
"args"]) || isset($trace[$i][
"params"])){
440 if(isset($trace[$i][
"args"])){
441 $args = $trace[$i][
"args"];
443 $args = $trace[$i][
"params"];
449 foreach($args as $argId => $value){
450 $paramsList[] = ($argId === $offset ?
"" :
"$argId: ") . self::stringifyValueForTrace($value, $maxStringLength);
453 $params = implode(
", ", $paramsList);
455 $messages[] =
"#$i " .
456 (isset($trace[$i][
"file"]) ? Filesystem::cleanPath($trace[$i][
"file"]) :
"") .
457 "(" . (isset($trace[$i][
"line"]) ? $trace[$i][
"line"] :
"") .
"): " .
458 (isset($trace[$i][
"class"]) ?
459 $trace[$i][
"class"] . (($trace[$i][
"type"] ===
"dynamic" || $trace[$i][
"type"] ===
"->") ?
"->" :
"::") :
462 $trace[$i][
"function"] .
463 "(" . Utils::printable($params) .
")";
478 $printableTrace = self::printableTrace($rawTrace, $maxStringLength);
480 foreach($printableTrace as $frameId => $printableFrame){
481 $rawFrame = $rawTrace[$frameId];
484 $rawFrame[
"file"] ??
null,
485 $rawFrame[
"line"] ?? 0
498 if(function_exists(
"xdebug_get_function_stack") && count($trace = @xdebug_get_function_stack()) !== 0){
499 $trace = array_reverse($trace);
501 $e = new \Exception();
502 $trace = $e->getTrace();
504 for($i = 0; $i < $skipFrames; ++$i){
507 return array_values($trace);
514 return self::printableTrace(self::currentTrace(++$skipFrames));
523 $rawDocComment = substr($docComment, 3, -2);
524 preg_match_all(
'/(*ANYCRLF)^[\t ]*(?:\* )?@([a-zA-Z\-]+)(?:[\t ]+(.+?))?[\t ]*$/m', $rawDocComment, $matches);
526 return array_combine($matches[1], $matches[2]);
534 $baseInterface = false;
535 if(!class_exists($baseName)){
536 if(!interface_exists($baseName)){
537 throw new \InvalidArgumentException(
"Base class $baseName does not exist");
539 $baseInterface =
true;
541 if(!class_exists($className)){
542 throw new \InvalidArgumentException(
"Class $className does not exist or is not a class");
544 if(!is_a($className, $baseName,
true)){
545 throw new \InvalidArgumentException(
"Class $className does not " . ($baseInterface ?
"implement" :
"extend") .
" $baseName");
547 $class = new \ReflectionClass($className);
548 if(!$class->isInstantiable()){
549 throw new \InvalidArgumentException(
"Class $className cannot be constructed");
567 $signature = CallbackType::createFromCallable($signature);
569 if(!$signature->isSatisfiedBy($subject)){
570 throw new \TypeError(
"Declaration of callable `" . CallbackType::createFromCallable($subject) .
"` must be compatible with `" . $signature .
"`");
580 foreach(
Utils::promoteKeys($array) as $k => $v){
583 }
catch(\TypeError $e){
584 throw new \TypeError(
"Incorrect type of element at \"$k\": " . $e->getMessage(), 0, $e);
600 foreach($array as $key => $value){
601 yield (
string) $key => $value;
617 public static function checkUTF8(
string $string) : void{
618 if(!mb_check_encoding($string,
'UTF-8')){
619 throw new \InvalidArgumentException(
"Text must be valid UTF-8");
629 public static function assumeNotFalse(mixed $value, \Closure|
string $context =
"This should never be false") : mixed{
630 if($value === false){
631 throw new AssumptionFailedError(
"Assumption failure: " . (is_string($context) ? $context : $context()) .
" (THIS IS A BUG)");
636 public static function checkFloatNotInfOrNaN(
string $name,
float $float) : void{
638 throw new \InvalidArgumentException(
"$name cannot be NaN");
640 if(is_infinite($float)){
641 throw new \InvalidArgumentException(
"$name cannot be infinite");
645 public static function checkVector3NotInfOrNaN(Vector3 $vector3) : void{
646 if($vector3 instanceof Location){
647 self::checkFloatNotInfOrNaN(
"yaw", $vector3->yaw);
648 self::checkFloatNotInfOrNaN(
"pitch", $vector3->pitch);
650 self::checkFloatNotInfOrNaN(
"x", $vector3->x);
651 self::checkFloatNotInfOrNaN(
"y", $vector3->y);
652 self::checkFloatNotInfOrNaN(
"z", $vector3->z);
655 public static function checkLocationNotInfOrNaN(Location $location) : void{
656 self::checkVector3NotInfOrNaN($location);
665 function_exists(
'opcache_get_status') &&
666 ($opcacheStatus = opcache_get_status(false)) !== false &&
667 isset($opcacheStatus[
"jit"][
"on"])
669 $jit = $opcacheStatus[
"jit"];
670 if($jit[
"on"] ===
true){
671 return (($jit[
"opt_flags"] >> 2) * 1000) +
672 (($jit[
"opt_flags"] & 0x03) * 100) +
673 ($jit[
"kind"] * 10) +
690 return mt_rand() / mt_getrandmax();