BinaryUtils   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 32
c 1
b 0
f 0
dl 0
loc 79
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A rleDecode() 0 16 3
A base64UrlDecode() 0 3 1
A base64UrlEncode() 0 3 1
A positiveModulo() 0 7 2
A rleEncode() 0 18 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sysbot\Bin\Common;
6
7
trait BinaryUtils
8
{
9
10
    /**
11
     * @param string $string
12
     * @return string
13
     */
14
    public static function rleEncode(string $string): string
15
    {
16
        $new = '';
17
        $count = 0;
18
        $null = chr(0);
19
        $chars = str_split($string);
20
        foreach ($chars as $char) {
21
            if ($char === $null) {
22
                $count++;
23
                continue;
24
            }
25
            if ($count > 0) {
26
                $new .= $null . chr($count);
27
                $count = 0;
28
            }
29
            $new .= $char;
30
        }
31
        return $new;
32
    }
33
34
    /**
35
     * @param string $string
36
     * @return string
37
     */
38
    public static function rleDecode(string $string): string
39
    {
40
        $new = '';
41
        $last = '';
42
        $null = chr(0);
43
        $chars = str_split($string);
44
        foreach ($chars as $char) {
45
            if ($last === $null) {
46
                $new .= str_repeat($last, ord($char));
47
                $last = '';
48
                continue;
49
            }
50
            $new .= $last;
51
            $last = $char;
52
        }
53
        return $new . $last;
54
    }
55
56
    /**
57
     * @param string $string
58
     * @return string
59
     */
60
    public static function base64UrlDecode(string $string): string
61
    {
62
        return base64_decode(str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT));
63
    }
64
65
    /**
66
     * @param string $string
67
     * @return string
68
     */
69
    public static function base64UrlEncode(string $string): string
70
    {
71
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($string));
72
    }
73
74
    /**
75
     * @param int $a
76
     * @param int $b
77
     * @return int
78
     */
79
    public static function positiveModulo(int $a, int $b): int
80
    {
81
        $remainder = $a % $b;
82
        if ($remainder < 0) {
83
            $remainder += abs($b);
84
        }
85
        return (int)$remainder;
86
    }
87
88
}