Completed
Push — master ( 700bb2...2360f5 )
by Philip
02:02
created

AbstractCRC32::calculate()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 23
Ratio 100 %

Importance

Changes 0
Metric Value
dl 23
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 12
nc 6
nop 1
1
<?php
2
3
namespace PBurggraf\CRC\CRC32;
4
5
use PBurggraf\CRC\AbstractCRC;
6
7
/**
8
 * @author Philip Burggraf <[email protected]>
9
 */
10 View Code Duplication
abstract class AbstractCRC32 extends AbstractCRC
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
11
{
12
    /**
13
     * @param string $buffer
14
     *
15
     * @return int
16
     */
17
    public function calculate(string $buffer): int
18
    {
19
        $crc = $this->init;
20
21
        $bufferLength = strlen($buffer);
22
23
        for ($bufferPosition = 0; $bufferPosition < $bufferLength; ++$bufferPosition) {
24
            $character = ord($buffer[$bufferPosition]);
25
26
            if ($this->reverseIn) {
27
                $character = $this->binaryReverse($character, 8);
28
            }
29
30
            $crc = $this->lookupTable[(($crc >> 24) ^ $character) & 0xff] ^ ($crc << 8);
31
            $crc &= 0xffffffff;
32
        }
33
34
        if ($this->reverseOut) {
35
            $crc = $this->binaryReverse($crc, 32);
36
        }
37
38
        return $crc ^ $this->xorOut;
39
    }
40
41
    /**
42
     * @param int $polynomial
43
     *
44
     * @return array
45
     */
46
    public function generateTable(int $polynomial): array
47
    {
48
        $tableSize = 256;
49
50
        $table = [];
51
52
        for ($iterator = 0; $iterator < $tableSize; ++$iterator) {
53
            $temp = 0;
54
            $a = ($iterator << 24);
55
            for ($j = 0; $j < 8; ++$j) {
56
                if ((($temp ^ $a) & 0x80000000) !== 0) {
57
                    $temp = (($temp << 1) ^ $polynomial);
58
                } else {
59
                    $temp <<= 1;
60
                }
61
                $a <<= 1;
62
            }
63
            $table[$iterator] = $temp & 0xffffffff;
64
        }
65
66
        return $table;
67
    }
68
}
69