Base10And62Converter   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
c 0
b 0
f 0
lcom 0
cbo 0
dl 0
loc 45
ccs 15
cts 15
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A base10To62() 0 14 2
A base62To10() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nastoletni\Code\Application;
6
7
/**
8
 * @see https://stackoverflow.com/a/4964352
9
 */
10
class Base10And62Converter
11
{
12
    private const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
13
14
    /**
15
     * Converts base 10 [0-9] number to base 62 [0-9a-zA-Z].
16
     *
17
     * @param int $number
18
     *
19
     * @return string
20
     */
21 9
    public static function base10To62(int $number): string
22
    {
23 9
        $r = $number % 62;
24 9
        $result = static::ALPHABET[$r];
25 9
        $q = floor($number / 62);
26
27 9
        while ($q) {
28 4
            $r = $q % 62;
29 4
            $q = floor($q / 62);
30 4
            $result = static::ALPHABET[$r].$result;
31
        }
32
33 9
        return $result;
34
    }
35
36
    /**
37
     * Converts base 62 number [0-9a-zA-Z] to base 10 [0-9].
38
     *
39
     * @param string $number
40
     *
41
     * @return int
42
     */
43 8
    public static function base62To10(string $number): int
44
    {
45 8
        $limit = strlen($number);
46 8
        $result = strpos(static::ALPHABET, $number[0]);
47
48 8
        for ($i = 1; $i < $limit; $i++) {
49 4
            $result = 62 * $result + strpos(static::ALPHABET, $number[$i]);
50
        }
51
52 8
        return $result;
53
    }
54
}
55