TChecksum::computeCheckSum()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 1
1
<?php
2
3
namespace kalanis\RemoteRequest\Protocols\Fsp\Traits;
4
5
6
/**
7
 * Trait TChecksum
8
 * @package kalanis\RemoteRequest\Protocols\Fsp\Traits
9
 * Process checksums
10
11
/-* assume that we have already zeroed checksum in packet - that means set it to zero - chr(0) *-/
12
unsigned int sum,checksum;
13
 unsigned char *t;
14
 for(t = packet_start, sum = 0; t < packet_end; sum += *t++);
15
 checksum= sum + (sum >> 8);
16
17
 * PHP, Perl
18
 $len = strlen($packet);
19
 $packet[1] = chr(0); // at first null checksum in packet
20
 $sum = 0; // or $len for client->server
21
 for ($i = 0; $i < $len; $i++) {
22
     $sum += ord($packet[$i]);
23
 }
24
 $checksum = ($sum + ($sum >> 8));
25
 $byteChecksum = $checksum & 0xff;
26
 */
27
trait TChecksum
28
{
29
    /*
30
     * Slower, can be understand and ported
31
     */
32
//    protected function computeCheckSum(): int
33
//    {
34
//        $data = $this->getChecksumPacket();
35
//        $len = strlen($data);
36
//        $sum = $this->getInitialSumChunk();
37
//        for ($i = 0; $i < $len; $i++) {
38
//            $sum += ord($data[$i]);
39
////            print_r(['chkcc', $i, ord($data[$i]), $sum]);
40
//        }
41
//        $checksum = ($sum + ($sum >> 8));
42
////        var_dump(['chks', $sum, decbin($sum), decbin($sum >> 8)]);
43
//        return $checksum & 0xff; // only byte
44
//    }
45
46
    /*
47
     * Faster, less intelligible
48
     */
49 33
    protected function computeCheckSum(): int
50
    {
51 33
        $sum = array_reduce((array) str_split($this->getChecksumPacket()), [$this, 'sumBytes'], $this->getInitialSumChunk());
52 33
        return ($sum + ($sum >> 8)) & 0xff;
53
    }
54
55
    abstract protected function getChecksumPacket(): string;
56
57
    abstract protected function getInitialSumChunk(): int;
58
59 33
    public function sumBytes(int $sum, string $char): int
60
    {
61 33
        return $sum + ord($char);
62
    }
63
}
64