Conditions | 10 |
Paths | 16 |
Total Lines | 43 |
Code Lines | 25 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
1 | <?php |
||
117 | public function read(int $numBits):int{ |
||
118 | |||
119 | if($numBits < 1 || $numBits > 32 || $numBits > $this->available()){ |
||
120 | throw new InvalidArgumentException('invalid $numBits: '.$numBits); |
||
121 | } |
||
122 | |||
123 | $result = 0; |
||
124 | |||
125 | // First, read remainder from current byte |
||
126 | if($this->bitsRead > 0){ |
||
127 | $bitsLeft = 8 - $this->bitsRead; |
||
128 | $toRead = $numBits < $bitsLeft ? $numBits : $bitsLeft; |
||
129 | $bitsToNotRead = $bitsLeft - $toRead; |
||
130 | $mask = (0xff >> (8 - $toRead)) << $bitsToNotRead; |
||
131 | $result = ($this->buffer[$this->bytesRead] & $mask) >> $bitsToNotRead; |
||
132 | $numBits -= $toRead; |
||
133 | $this->bitsRead += $toRead; |
||
134 | |||
135 | if($this->bitsRead == 8){ |
||
136 | $this->bitsRead = 0; |
||
137 | $this->bytesRead++; |
||
138 | } |
||
139 | } |
||
140 | |||
141 | // Next read whole bytes |
||
142 | if($numBits > 0){ |
||
143 | |||
144 | while($numBits >= 8){ |
||
145 | $result = ($result << 8) | ($this->buffer[$this->bytesRead] & 0xff); |
||
146 | $this->bytesRead++; |
||
147 | $numBits -= 8; |
||
148 | } |
||
149 | |||
150 | // Finally read a partial byte |
||
151 | if($numBits > 0){ |
||
152 | $bitsToNotRead = 8 - $numBits; |
||
153 | $mask = (0xff >> $bitsToNotRead) << $bitsToNotRead; |
||
154 | $result = ($result << $numBits) | (($this->buffer[$this->bytesRead] & $mask) >> $bitsToNotRead); |
||
155 | $this->bitsRead += $numBits; |
||
156 | } |
||
157 | } |
||
158 | |||
159 | return $result; |
||
160 | } |
||
163 |