Issues (14)

src/Protocol/Binary.php (1 issue)

1
<?php
2
/**
3
 * Binary ops
4
 * User: moyo
5
 * Date: 27/02/2018
6
 * Time: 2:14 PM
7
 */
8
9
namespace Carno\NSQ\Protocol;
10
11
class Binary
12
{
13
    /**
14
     * Read and unpack short (2 bytes) from buffer
15
     * @param Buffer $buffer
16
     * @return int
17
     */
18
    public static function short(Buffer $buffer) : ?int
19
    {
20
        return unpack('n', $buffer->read(2))[1] ?? null;
21
    }
22
23
    /**
24
     * Read and unpack integer (4 bytes) from buffer
25
     * @param Buffer $buffer
26
     * @return int
27
     */
28
    public static function int(Buffer $buffer) : ?int
29
    {
30
        return ($up = unpack('N', $buffer->read(4))[1] ?? null) ? sprintf('%u', $up) : null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $up = unpack('N',...rintf('%u', $up) : null could return the type string which is incompatible with the type-hinted return integer|null. Consider adding an additional type-check to rule them out.
Loading history...
31
    }
32
33
    /**
34
     * Read and unpack long (8 bytes) from buffer
35
     * @param Buffer $buffer
36
     * @return string
37
     */
38
    public static function long(Buffer $buffer) : ?string
39
    {
40
        return is_array($hi = unpack('N', $buffer->read(4))) && is_array($lo = unpack('N', $buffer->read(4)))
41
            ? bcadd(bcmul(sprintf('%u', $hi[1]), '4294967296'), sprintf('%u', $lo[1]))
42
            : null
43
        ;
44
    }
45
46
    /**
47
     * Read raw string from buffer
48
     * @param Buffer $buffer
49
     * @param int $size
50
     * @return string
51
     */
52
    public static function string(Buffer $buffer, int $size) : string
53
    {
54
        return $buffer->read($size);
55
    }
56
}
57