Completed
Push — master ( dba287...8d738d )
by Daniel
13:35
created

ByteOrderAwareTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 2
cbo 2
dl 0
loc 64
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getByteOrder() 0 8 2
A setByteOrder() 0 9 2
A getMachineByteOrder() 0 13 3
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\ByteOrder;
9
10
use GravityMedia\Stream\Exception;
11
12
/**
13
 * Byte order aware trait
14
 *
15
 * @package GravityMedia\Stream\ByteOrder
16
 */
17
trait ByteOrderAwareTrait
18
{
19
    /**
20
     * @var int
21
     */
22
    protected $byteOrder;
23
24
    /**
25
     * @var int
26
     */
27
    protected static $machineByteOrder;
28
29
    /**
30
     * Get byte order
31
     *
32
     * @return int
33
     */
34
    public function getByteOrder()
35
    {
36
        if (null === $this->byteOrder) {
37
            return ByteOrder::MACHINE_ENDIAN;
38
        }
39
40
        return $this->byteOrder;
41
    }
42
43
    /**
44
     * Set byteOrder
45
     *
46
     * @param int $byteOrder
47
     *
48
     * @throws Exception\InvalidArgumentException An exception will be thrown for invalid byte order arguments
49
     *
50
     * @return $this
51
     */
52
    public function setByteOrder($byteOrder)
53
    {
54
        if (!in_array($byteOrder, ByteOrder::values())) {
55
            throw new Exception\InvalidArgumentException('Invalid byte order');
56
        }
57
58
        $this->byteOrder = $byteOrder;
59
        return $this;
60
    }
61
62
    /**
63
     * Get machine byte order
64
     *
65
     * @return int
66
     */
67
    public function getMachineByteOrder()
68
    {
69
        if (null === static::$machineByteOrder) {
70
            static::$machineByteOrder = ByteOrder::BIG_ENDIAN;
71
72
            list(, $value) = unpack('l*', "\x01\x00\x00\x00");
73
            if (1 === $value) {
74
                static::$machineByteOrder = ByteOrder::LITTLE_ENDIAN;
75
            }
76
        }
77
78
        return static::$machineByteOrder;
79
    }
80
}
81