1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is a part of Woketo package. |
4
|
|
|
* |
5
|
|
|
* (c) Nekland <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full license, take a look to the LICENSE file |
8
|
|
|
* on the root directory of this project |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Nekland\Woketo\Rfc6455; |
12
|
|
|
|
13
|
|
|
use Nekland\Woketo\Utils\BitManipulation; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class FrameFactory |
17
|
|
|
* |
18
|
|
|
* This class generates Frame objects for control frames. |
19
|
|
|
* https://tools.ietf.org/html/rfc6455#section-5.5 |
20
|
|
|
* |
21
|
|
|
* Notice: a control frame cannot be larger than 125 bytes. |
22
|
|
|
*/ |
23
|
|
|
class FrameFactory |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Configuration for frames creation |
27
|
|
|
* |
28
|
|
|
* @var array |
29
|
|
|
*/ |
30
|
|
|
private $configuration; |
31
|
|
|
|
32
|
|
|
public function __construct(array $configuration = []) |
33
|
|
|
{ |
34
|
|
|
$this->configuration = $configuration; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param int $status One of the close constant code of Frame class. |
39
|
|
|
* @param string $reason A little message that explain why closing. |
40
|
|
|
* @return Frame |
41
|
|
|
*/ |
42
|
|
|
public function createCloseFrame(int $status = Frame::CLOSE_NORMAL, string $reason = null) : Frame |
43
|
|
|
{ |
44
|
|
|
$frame = $this->createNewFrame(); |
45
|
|
|
|
46
|
|
|
$frame->setOpcode(Frame::OP_CLOSE); |
47
|
|
|
$content = BitManipulation::intToString($status); |
48
|
|
|
if (null !== $reason) { |
49
|
|
|
$content .= $reason; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$frame->setPayload($content); |
53
|
|
|
|
54
|
|
|
return $frame; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param string $payload The payload must be the message content of the Ping |
59
|
|
|
* @return Frame |
60
|
|
|
*/ |
61
|
|
|
public function createPongFrame(string $payload) : Frame |
62
|
|
|
{ |
63
|
|
|
$frame = $this->createNewFrame(); |
64
|
|
|
|
65
|
|
|
$frame->setOpcode(Frame::OP_PONG); |
66
|
|
|
$frame->setPayload($payload); |
67
|
|
|
|
68
|
|
|
return $frame; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Construct a frame with a global configuration. |
73
|
|
|
* |
74
|
|
|
* @param string|null $rawData |
75
|
|
|
* @return Frame |
76
|
|
|
*/ |
77
|
|
|
public function createNewFrame(string $rawData = null) |
78
|
|
|
{ |
79
|
|
|
return new Frame($rawData, $this->configuration); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* This generates a string of 4 random bytes. (WebSocket mask according to the RFC) |
84
|
|
|
* |
85
|
|
|
* @return string |
86
|
|
|
*/ |
87
|
|
|
public static function generateMask() : string |
88
|
|
|
{ |
89
|
|
|
return random_bytes(4); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|