common.php (2009B)
1 <?php 2 3 declare(strict_types=1); 4 5 namespace Arboricx; 6 7 require __DIR__ . '/ffi.php'; 8 9 use function Arboricx\{ctx_init, ctx_free, loadBundleDefault, ofNumber, ofString, app, reduce, toString, toBool, toNumber}; 10 11 function findLib(): string 12 { 13 $env = getenv('ARBORICX_LIB'); 14 if ($env !== false && file_exists($env)) { 15 return $env; 16 } 17 18 $paths = [ 19 __DIR__ . '/../../zig/zig-out/lib/libarboricx.so', 20 __DIR__ . '/../libarboricx.so', 21 '/usr/local/lib/libarboricx.so', 22 '/usr/lib/libarboricx.so', 23 './libarboricx.so', 24 ]; 25 foreach ($paths as $p) { 26 if (file_exists($p)) { 27 return $p; 28 } 29 } 30 31 throw new \RuntimeException('libarboricx.so not found. Set ARBORICX_LIB to its full path.'); 32 } 33 34 function decode(\FFI\CData $ctx, int $root): string 35 { 36 try { 37 return toBool($ctx, $root) ? 'true' : 'false'; 38 } catch (\Throwable $e) { 39 try { 40 return toString($ctx, $root); 41 } catch (\Throwable $e2) { 42 try { 43 return (string) toNumber($ctx, $root); 44 } catch (\Throwable $e3) { 45 throw new \RuntimeException('could not decode result'); 46 } 47 } 48 } 49 } 50 51 function decodeType(\FFI\CData $ctx, int $root): string 52 { 53 try { 54 toBool($ctx, $root); 55 return 'bool'; 56 } catch (\Throwable $e) { 57 try { 58 toString($ctx, $root); 59 return 'string'; 60 } catch (\Throwable $e2) { 61 try { 62 toNumber($ctx, $root); 63 return 'number'; 64 } catch (\Throwable $e3) { 65 return 'unknown (raw tree)'; 66 } 67 } 68 } 69 } 70 71 function readBundle(string $path): string 72 { 73 if (!file_exists($path)) { 74 throw new \RuntimeException("bundle not found: $path"); 75 } 76 $bytes = file_get_contents($path); 77 if ($bytes === false) { 78 throw new \RuntimeException("could not read bundle: $path"); 79 } 80 return $bytes; 81 }