$source, 'destination' => $destination, 'namespace' => $namespace, 'payload' => $json])); } public static function frame(string $message): string { return pack('N', strlen($message)) . $message; } /** * The whole frames at the start of $buffer, taken out of it (what is left waits for more bytes). * @return list * @throws \RuntimeException a frame too big or not a CastMessage (the connection is not a Cast device) */ public static function unframe(string &$buffer): array { $out = []; while (strlen($buffer) >= 4) { $length = (int)unpack('N', substr($buffer, 0, 4))[1]; if ($length < 0 || $length > self::MAX_FRAME) { throw new \RuntimeException('trame Cast invalide'); } if (strlen($buffer) < 4 + $length) { break; } $out[] = self::decode(substr($buffer, 4, $length)); $buffer = (string)substr($buffer, 4 + $length); } return $out; } /** * @return array{source: string, destination: string, namespace: string, payload: string, binary: ?string, version: int} * @throws \RuntimeException not a CastMessage */ public static function decode(string $bytes): array { $m = ['source' => '', 'destination' => '', 'namespace' => '', 'payload' => '', 'binary' => null, 'version' => 0]; $i = 0; $n = strlen($bytes); while ($i < $n) { $key = self::readVarint($bytes, $i); $field = $key >> 3; $wire = $key & 7; if ($wire === 0) { $value = self::readVarint($bytes, $i); if ($field === 1) { $m['version'] = $value; } } elseif ($wire === 2) { $length = self::readVarint($bytes, $i); if ($i + $length > $n) { throw new \RuntimeException('message Cast tronqué'); } $value = substr($bytes, $i, $length); $i += $length; match ($field) { 2 => $m['source'] = $value, 3 => $m['destination'] = $value, 4 => $m['namespace'] = $value, 6 => $m['payload'] = $value, 7 => $m['binary'] = $value, default => null, }; } elseif ($wire === 5) { $i += 4; } elseif ($wire === 1) { $i += 8; } else { throw new \RuntimeException('message Cast illisible'); } } if ($i > $n) { throw new \RuntimeException('message Cast tronqué'); } return $m; } private static function key(int $field, int $wire): string { return self::varint($field << 3 | $wire); } public static function varint(int $value): string { $out = ''; while ($value > 0x7F) { $out .= chr(($value & 0x7F) | 0x80); $value >>= 7; } return $out . chr($value); } private static function bytes(string $s): string { return self::varint(strlen($s)) . $s; } private static function readVarint(string $bytes, int &$i): int { $value = 0; $shift = 0; $n = strlen($bytes); while (true) { if ($i >= $n || $shift > 28) { throw new \RuntimeException('message Cast tronqué'); } $b = ord($bytes[$i++]); $value |= ($b & 0x7F) << $shift; if ($b < 0x80) { return $value; } $shift += 7; } } }