HuffmanNodeQueue::getOnlyNode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
dl 0
loc 6
rs 10
c 1
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Mfonte\Base62x\Compression\Huffman;
4
5
use Mfonte\Base62x\Exception\CompressionException;
6
7
/**
8
 *	A queue of Huffman Nodes that need to be incorporated into a tree.
9
 */
10
class HuffmanNodeQueue
11
{
12
    private $nodes = [];
13
14
    /**
15
     * put the new node into the queue, keeping it in order by weight
16
     * NOTE: schliemel going on here!
17
     */
18
    public function addNode(HuffmanNode $node)
19
    {
20
        if (\count($this->nodes) == 0) {
21
            $this->nodes = [$node];
22
23
            return;
24
        }
25
26
        $index = 0;
27
        while (isset($this->nodes[$index]) && $this->nodes[$index]->getWeight() < $node->getWeight()) {
28
            ++$index;
29
        }
30
        array_splice($this->nodes, $index, 0, [$node]);
31
    }
32
33
    /**
34
     * 	get the two nodes with the lowest weights from the front of the queue.
35
     */
36
    public function popTwoNodes()
37
    {
38
        if (\count($this->nodes) > 1) {
39
            $first = array_shift($this->nodes);
40
            $second = array_shift($this->nodes);
41
42
            return [$first, $second];
43
        } else {
44
            return false;
45
        }
46
    }
47
48
    /**
49
     * 	once there's only one node left, extract it.
50
     */
51
    public function getOnlyNode()
52
    {
53
        if (\count($this->nodes) == 1) {
54
            return $this->nodes[0];
55
        } else {
56
            throw new CompressionException('huffman', 'Wrong number of nodes. Only call getOnlyNode when exactly one node exists.');
57
        }
58
    }
59
}
60