Completed
Push — master ( 44b0be...4a5c62 )
by Daniel
02:13
created

ByteOrderAwareTrait::getMachineByteOrder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 0
cts 9
cp 0
rs 9.4285
cc 3
eloc 7
nc 3
nop 0
crap 12
1
<?php
2
/**
3
 * This file is part of the stream package
4
 *
5
 * @author Daniel Schröder <[email protected]>
6
 */
7
8
namespace GravityMedia\Stream\Reader;
9
10
use GravityMedia\Stream\Enum\ByteOrder;
11
use GravityMedia\Stream\Exception;
12
13
/**
14
 * Short (16-bit integer) reader
15
 *
16
 * @package GravityMedia\Stream\Reader
17
 */
18
trait ByteOrderAwareTrait
19
{
20
    /**
21
     * @var int
22
     */
23
    protected $byteOrder;
24
25
    /**
26
     * @var int
27
     */
28
    protected static $machineByteOrder;
29
30
    /**
31
     * Get byte order
32
     *
33
     * @return int
34
     */
35
    public function getByteOrder()
36
    {
37
        if (null === $this->byteOrder) {
38
            return ByteOrder::MACHINE_ENDIAN;
39
        }
40
41
        return $this->byteOrder;
42
    }
43
44
    /**
45
     * Set byteOrder
46
     *
47
     * @param int $byteOrder
48
     *
49
     * @throws Exception\InvalidArgumentException An exception will be thrown for invalid byte order arguments
50
     *
51
     * @return $this
52
     */
53
    public function setByteOrder($byteOrder)
54
    {
55
        if (!in_array($byteOrder, ByteOrder::values())) {
56
            throw new Exception\InvalidArgumentException('Invalid byte order');
57
        }
58
59
        $this->byteOrder = $byteOrder;
60
        return $this;
61
    }
62
63
    /**
64
     * Get machine byte order
65
     *
66
     * @return int
67
     */
68
    public function getMachineByteOrder()
69
    {
70
        if (null === static::$machineByteOrder) {
71
            static::$machineByteOrder = ByteOrder::BIG_ENDIAN;
72
73
            list(, $value) = unpack('l*', "\x01\x00\x00\x00");
74
            if (1 === $value) {
75
                static::$machineByteOrder = ByteOrder::LITTLE_ENDIAN;
76
            }
77
        }
78
79
        return static::$machineByteOrder;
80
    }
81
}
82