Base10And62Converter::base62To10()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 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