Completed
Push — master ( 50d673...58d71b )
by Michele
04:25
created

MSCompressedSection::getContents()   C

Complexity

Conditions 15
Paths 5

Size

Total Lines 65
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 15.0549

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 65
ccs 45
cts 48
cp 0.9375
rs 5.9352
cc 15
eloc 49
nc 5
nop 2
crap 15.0549

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace CHMLib\Section;
4
5
use Exception;
6
use CHMLib\CHM;
7
use CHMLib\Reader\StringReader;
8
use CHMLib\Reader\BitReader;
9
use CHMLib\Header\LZXC;
10
use CHMLib\LZX\Inflater;
11
use CHMLib\LZX\LRUCache;
12
13
/**
14
 * Represent a LXZ-compressed section of data in a CHM file.
15
 */
16
class MSCompressedSection extends Section
17
{
18
    /**
19
     * The LZX reset interval.
20
     *
21
     * @var int
22
     */
23
    protected $resetInterval;
24
25
    /**
26
     * The window size.
27
     *
28
     * @var int
29
     */
30
    protected $windowSize;
31
32
    /**
33
     * The size of the uncompressed data.
34
     *
35
     * @var int
36
     */
37
    protected $uncompressedLength;
38
39
    /**
40
     * The size of the compressed data.
41
     *
42
     * @var int
43
     */
44
    protected $compressedLength;
45
46
    /**
47
     * The block size.
48
     *
49
     * @var int
50
     */
51
    protected $blockSize;
52
53
    /**
54
     * The address table.
55
     *
56
     * @var int[]
57
     */
58
    protected $addressTable;
59
60
    /**
61
     * The currently cached blocks.
62
     *
63
     * @var LRUCache
64
     */
65
    protected $cachedBlocks;
66
67
    /**
68
     * Initializes the instance.
69
     *
70
     * @param CHM $chm The parent CHM file.
71
     *
72
     * @throws Exception Throws an Exception in case of errors.
73
     */
74 4
    public function __construct(CHM $chm)
75
    {
76 4
        parent::__construct($chm);
77 4
        $controlDataEntry = $chm->getEntryByPath('::DataSpace/Storage/MSCompressed/ControlData');
78 4
        if ($controlDataEntry === null) {
79
            throw new Exception("Missing required entry: '::DataSpace/Storage/MSCompressed/ControlData'");
80
        }
81 4
        if ($controlDataEntry->getContentSectionIndex() !== 0) {
82
            throw new Exception("The content of the entry '{$controlDataEntry->getPath()}' should be in section 0, but it's in section {$controlDataEntry->getContentSectionIndex()}");
83
        }
84 4
        $controlDataReader = new StringReader($controlDataEntry->getContents());
85 4
        $lzxc = new LZXC($controlDataReader);
86 4
        $this->resetInterval = $lzxc->getResetInterval();
87 4
        $this->windowSize = $lzxc->getWindowSize() * 32768;
88 4
        $this->cachedBlocks = new LRUCache((1 + $lzxc->getCacheSize()) << 2);
89 4
        $resetTableEntry = $chm->getEntryByPath('::DataSpace/Storage/MSCompressed/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable');
90 4
        if ($resetTableEntry === null) {
91
            throw new Exception("Missing required entry: '::DataSpace/Storage/MSCompressed/Transform/{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable'");
92
        }
93 4
        if ($resetTableEntry->getContentSectionIndex() !== 0) {
94
            throw new Exception("The content of the entry '{$resetTableEntry->getPath()}' should be in section 0, but it's in section {$resetTableEntry->getContentSectionIndex()}");
95
        }
96 4
        $resetTableReader = new StringReader($resetTableEntry->getContents());
97 4
        $resetTableVersion = $resetTableReader->readUInt32();
98 4
        if ($resetTableVersion !== 2) {
99
            throw new Exception("Unsupported LZX Reset Table version: $resetTableVersion");
100
        }
101 4
        $addressTableSize = $resetTableReader->readUInt32();
102 4
        /* Size of table entry (8) */ $resetTableReader->readUInt32();
103 4
        /* Header length (40) */ $resetTableReader->readUInt32();
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
104 4
        $this->uncompressedLength = $resetTableReader->readUInt64();
0 ignored issues
show
Documentation Bug introduced by
It seems like $resetTableReader->readUInt64() can also be of type double. However, the property $uncompressedLength is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
105 4
        $this->compressedLength = $resetTableReader->readUInt64();
0 ignored issues
show
Documentation Bug introduced by
It seems like $resetTableReader->readUInt64() can also be of type double. However, the property $compressedLength is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
106 4
        $this->blockSize = $resetTableReader->readUInt64(); // We do not support block sizes bigger than 32-bit integers
0 ignored issues
show
Documentation Bug introduced by
It seems like $resetTableReader->readUInt64() can also be of type double. However, the property $blockSize is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
107 4
        $this->addressTable = array();
108 4
        for ($i = 0; $i < $addressTableSize; ++$i) {
109 4
            $this->addressTable[$i] = $resetTableReader->readUInt64();
110
        }
111 4
        $contentEntry = $chm->getEntryByPath('::DataSpace/Storage/MSCompressed/Content');
112 4
        if ($contentEntry === null) {
113
            throw new Exception("Missing required entry: '::DataSpace/Storage/MSCompressed/Content");
114
        }
115 4
        if ($this->compressedLength > $contentEntry->getLength()) {
116
            throw new Exception("Compressed section size should be {$this->compressedLength}, but it's {$contentEntry->getLength()}");
117
        }
118 4
        $this->sectionOffset = $chm->getITSF()->getContentOffset() + $contentEntry->getOffset();
119 4
    }
120
121
    /**
122
     * {@inheritdoc}
123
     *
124
     * @see Section::getContents()
125
     */
126 485
    public function getContents($offset, $length)
127
    {
128 485
        $result = '';
129 485
        if ($length > 0) {
130 483
            $startBlockNo = (int) ($offset / $this->blockSize);
131 483
            $startOffset = $offset % $this->blockSize;
132 483
            $endBlockNo = (int) (($offset + $length) / $this->blockSize);
133 483
            $endOffset = (int) (($offset + $length) % $this->blockSize);
134 483
            if ($endOffset === 0 && $endBlockNo > $startBlockNo) {
135
                $endOffset = $this->blockSize;
136
                --$endBlockNo;
137
            }
138 483
            $blockNo = $startBlockNo - $startBlockNo % $this->resetInterval;
139 483
            $inflater = new Inflater($this->windowSize);
140
141 483
            $buf = array();
0 ignored issues
show
Unused Code introduced by
$buf is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
142 483
            $pos = 0;
143 483
            $bytesLeft = 0;
144 483
            $reader = $this->chm->getReader();
145 483
            while ($bytesLeft > 0 || $blockNo <= $endBlockNo) {
146 483
                $data = '';
147 483
                while ($bytesLeft <= 0) {
148
                    // Read block
149 483
                    if ($blockNo > $endBlockNo) {
150
                        throw new Exception('Read after last data block');
151
                    }
152 483
                    $cacheNo = (int) ($blockNo / $this->resetInterval);
153 483
                    $cache = $this->cachedBlocks->get($cacheNo);
154 483
                    if ($cache === null) {
155 26
                        $this->cachedBlocks->prune();
156 26
                        $cache = array();
157 26
                        $resetBlockNo = $blockNo - $blockNo % $this->resetInterval;
158 26
                        for ($i = 0; $i < $this->resetInterval && $resetBlockNo + $i < count($this->addressTable); ++$i) {
159 26
                            $thisBlockNo = $resetBlockNo + $i;
160 26
                            $len = ($thisBlockNo + 1 < count($this->addressTable)) ?
161 23
                                ($this->addressTable[$thisBlockNo + 1] - $this->addressTable[$thisBlockNo])
162
                                :
163 26
                                ($this->compressedLength - $this->addressTable[$thisBlockNo]);
164 26
                            $reader->setPosition($this->sectionOffset + $this->addressTable[$thisBlockNo]);
165 26
                            $bitReader = new BitReader($reader->readString($len));
166 26
                            $cache[$i] = $inflater->inflate(
167 26
                                $i === 0,
168
                                $bitReader,
169 26
                                $this->blockSize
170
                            );
171
                        }
172 26
                        $this->cachedBlocks->put($cacheNo, $cache);
173
                    }
174 483
                    $data = $cache[$blockNo % $this->resetInterval];
175
                    // the start block has special pos value
176 483
                    $pos = ($blockNo === $startBlockNo) ? $startOffset : 0;
177
                    // the end block has special length
178 483
                    $bytesLeft = ($blockNo < $startBlockNo) ? 0 : (($blockNo < $endBlockNo) ? $this->blockSize : $endOffset);
179 483
                    $bytesLeft -= $pos;
180 483
                    ++$blockNo;
181
                }
182 483
                $togo = $bytesLeft;
183 483
                $result .= substr($data, $pos, $togo);
184 483
                $pos += $togo;
185 483
                $bytesLeft -= $togo;
186
            }
187
        }
188
189 485
        return $result;
190
    }
191
}
192