-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPayloadFactory.php
More file actions
73 lines (57 loc) · 1.95 KB
/
PayloadFactory.php
File metadata and controls
73 lines (57 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace Spiral\RoadRunner;
use Spiral\Goridge\Frame;
use Spiral\RoadRunner\Exception\RoadRunnerException;
use Spiral\RoadRunner\Message\Command\GetProcessId;
use Spiral\RoadRunner\Message\Command\Pong;
use Spiral\RoadRunner\Message\Command\StreamStop;
use Spiral\RoadRunner\Message\Command\WorkerStop;
final class PayloadFactory
{
private const JSON_DECODE_FLAGS = \JSON_THROW_ON_ERROR;
public static function fromFrame(Frame $frame): Payload
{
$payload = $frame->payload ?? '';
if ($frame->hasFlag(Frame::CONTROL)) {
return self::makeControl($payload);
}
if (($frame->byte10 & Frame::BYTE10_STOP) !== 0) {
return new StreamStop($payload);
}
if (($frame->byte10 & Frame::BYTE10_PONG) !== 0) {
return new Pong($payload);
}
return new Payload(
\substr($payload, $frame->options[0]),
\substr($payload, 0, $frame->options[0]),
);
}
private static function makeControl(string $header): Payload
{
try {
$command = self::decode($header);
} catch (\JsonException $e) {
throw new RoadRunnerException('Invalid task header, JSON payload is expected: ' . $e->getMessage());
}
if (!empty($command['stop'])) {
return new WorkerStop(null, $header);
}
if (!empty($command['pid'])) {
return new GetProcessId(null, $header);
}
throw new RoadRunnerException('Invalid task header, undefined control package');
}
/**
* @throws \JsonException
* @psalm-assert non-empty-string $json
*/
private static function decode(string $json): array
{
$result = \json_decode($json, true, 512, self::JSON_DECODE_FLAGS);
if (! \is_array($result)) {
throw new \JsonException('Json message must be an array or object');
}
return $result;
}
}