Completed
Push — master ( e26ab3...1dd3f4 )
by Maxime
9s
created

FrameFactory::generateMask()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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