Completed
Push — master ( 104e68...b4839f )
by Maxime
12s
created

FrameFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 25
    public function __construct(array $configuration = [])
33
    {
34 25
        $this->configuration = $configuration;
35 25
    }
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 3
    public function createCloseFrame(int $status = Frame::CLOSE_NORMAL, string $reason = null) : Frame
43
    {
44 3
        $frame = $this->createNewFrame();
45
46 3
        $frame->setOpcode(Frame::OP_CLOSE);
47 3
        $content = BitManipulation::intToBinaryString($status);
48 3
        if (null !== $reason) {
49
            $content .= $reason;
50
        }
51
52 3
        $frame->setPayload($content);
53
54 3
        return $frame;
55
    }
56
57
    /**
58
     * @param string $payload The payload must be the message content of the Ping
59
     * @return Frame
60
     */
61 2
    public function createPongFrame(string $payload) : Frame
62
    {
63 2
        $frame = $this->createNewFrame();
64
65 2
        $frame->setOpcode(Frame::OP_PONG);
66 2
        $frame->setPayload($payload);
67
68 2
        return $frame;
69
    }
70
71
    /**
72
     * Construct a frame with a global configuration.
73
     *
74
     * @param string|null $rawData
75
     * @return Frame
76
     */
77 16
    public function createNewFrame(string $rawData = null)
78
    {
79 16
        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 1
    public static function generateMask() : string
88
    {
89 1
        return random_bytes(4);
90
    }
91
}
92