1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-11 16:49:51 +01:00
parallel/lib/Sync/ChannelParser.php

89 lines
2.5 KiB
PHP
Raw Normal View History

<?php
2017-11-10 18:35:47 +01:00
namespace Amp\Parallel\Sync;
use Amp\Parser\Parser;
2018-10-21 17:54:46 +02:00
final class ChannelParser extends Parser
2018-10-07 16:50:45 +02:00
{
const HEADER_LENGTH = 5;
/**
* @param callable(mixed $data) Callback invoked when data is parsed.
*/
2018-10-07 16:50:45 +02:00
public function __construct(callable $callback)
{
parent::__construct(self::parser($callback));
}
/**
* @param mixed $data Data to encode to send over a channel.
*
* @return string Encoded data that can be parsed by this class.
*
* @throws SerializationException
*/
2018-10-07 16:50:45 +02:00
public function encode($data): string
{
try {
$data = \serialize($data);
} catch (\Throwable $exception) {
throw new SerializationException(
\sprintf("The given data cannot be sent because it is not serializable: %s", $exception->getMessage()),
2018-10-25 06:02:24 +02:00
0,
2017-07-21 06:58:13 +02:00
$exception
);
}
return \pack("CL", 0, \strlen($data)) . $data;
}
/**
* @param callable $push
*
* @return \Generator
*
2020-02-15 00:33:38 +01:00
* @throws ChannelException
* @throws SerializationException
*/
private static function parser(callable $push): \Generator
2018-10-07 16:50:45 +02:00
{
while (true) {
$header = yield self::HEADER_LENGTH;
$data = \unpack("Cprefix/Llength", $header);
if ($data["prefix"] !== 0) {
$data = $header . yield;
throw new ChannelException("Invalid packet received: " . self::encodeUnprintableChars($data));
}
$data = yield $data["length"];
// Attempt to unserialize the received data.
try {
$result = \unserialize($data);
if ($result === false && $data !== \serialize(false)) {
throw new ChannelException("Received invalid data: " . self::encodeUnprintableChars($data));
}
} catch (\Throwable $exception) {
2018-10-25 05:49:01 +02:00
throw new SerializationException("Exception thrown when unserializing data", 0, $exception);
}
$push($result);
}
}
/**
* @param string $data Binary data.
*
* @return string Unprintable characters encoded as \x##.
*/
private static function encodeUnprintableChars(string $data): string
2018-10-07 16:50:45 +02:00
{
2019-08-28 01:14:56 +02:00
return \preg_replace_callback("/[^\x20-\x7e]/", function (array $matches): string {
return "\\x" . \dechex(\ord($matches[0]));
}, $data);
}
}