Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
55 / 55
100.00% covered (success)
100.00%
1 / 1
CRAP
n/a
0 / 0
Wikimedia\base_convert
100.00% covered (success)
100.00%
55 / 55
100.00% covered (success)
100.00%
1 / 1
23
1<?php
2declare( strict_types = 1 );
3
4/**
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace Wikimedia;
10
11/**
12 * Convert an arbitrarily-long string from one numeric base to
13 * another, optionally zero-padding to a minimum column width.
14 *
15 * Supports base 2 through 36; digit values 10-36 are represented
16 * as lowercase letters a-z. Input is case-insensitive.
17 *
18 * @param string $input Input number
19 * @param int $sourceBase Base of the input number
20 * @param int $destBase Desired base of the output
21 * @param int $pad Minimum number of digits in the output (pad with zeroes)
22 * @param bool $lowercase Whether to output in lowercase or uppercase
23 * @param string $engine Either "gmp", "bcmath", "php" or "auto" (default).
24 *  In the case of "auto", the other engines ("gmp" and "bcmath") are used in
25 *  the listed order in terms of preference if that PHP extension is actually loaded.
26 * @return string|false The output number as a string, or false on error
27 */
28function base_convert( $input, $sourceBase, $destBase, $pad = 1,
29    $lowercase = true, $engine = 'auto'
30) {
31    $input = (string)$input;
32    if (
33        $sourceBase < 2 ||
34        $sourceBase > 36 ||
35        $destBase < 2 ||
36        $destBase > 36 ||
37        $sourceBase !== (int)$sourceBase ||
38        $destBase !== (int)$destBase ||
39        $pad !== (int)$pad ||
40        !preg_match(
41            "/^[" . substr( '0123456789abcdefghijklmnopqrstuvwxyz', 0, $sourceBase ) . "]+$/i",
42            $input
43        )
44    ) {
45        return false;
46    }
47
48    static $baseChars = [
49        10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f',
50        16 => 'g', 17 => 'h', 18 => 'i', 19 => 'j', 20 => 'k', 21 => 'l',
51        22 => 'm', 23 => 'n', 24 => 'o', 25 => 'p', 26 => 'q', 27 => 'r',
52        28 => 's', 29 => 't', 30 => 'u', 31 => 'v', 32 => 'w', 33 => 'x',
53        34 => 'y', 35 => 'z',
54
55        '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5,
56        '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11,
57        'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17,
58        'i' => 18, 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23,
59        'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, 's' => 28, 't' => 29,
60        'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35
61    ];
62
63    if ( extension_loaded( 'gmp' ) && ( $engine === 'auto' || $engine === 'gmp' ) ) {
64        $result = gmp_strval( gmp_init( $input, $sourceBase ), $destBase );
65    } elseif ( extension_loaded( 'bcmath' ) && ( $engine === 'auto' || $engine === 'bcmath' ) ) {
66        $decimal = '0';
67        foreach ( str_split( strtolower( $input ) ) as $char ) {
68            $decimal = bcmul( $decimal, (string)$sourceBase );
69            $decimal = bcadd( $decimal, (string)$baseChars[$char] );
70        }
71
72        for ( $result = ''; bccomp( $decimal, '0' ); $decimal = bcdiv( $decimal, (string)$destBase, 0 ) ) {
73            // As of PHP 7.2, bcmod can return a floating point value if bcscale is nonzero
74            $result .= $baseChars[(int)bcmod( $decimal, (string)$destBase )];
75        }
76
77        $result = strrev( $result );
78    } else {
79        $inDigits = [];
80        foreach ( str_split( strtolower( $input ) ) as $char ) {
81            $inDigits[] = $baseChars[$char];
82        }
83
84        // Iterate over the input, modulo-ing out an output digit
85        // at a time until input is gone.
86        $result = '';
87        while ( $inDigits ) {
88            $work = 0;
89            $workDigits = [];
90
91            // Long division...
92            foreach ( $inDigits as $digit ) {
93                $work *= $sourceBase;
94                $work += $digit;
95
96                if ( $workDigits || $work >= $destBase ) {
97                    $workDigits[] = (int)( $work / $destBase );
98                }
99                $work %= $destBase;
100            }
101
102            // All that division leaves us with a remainder,
103            // which is conveniently our next output digit.
104            $result .= $baseChars[$work];
105
106            // And we continue!
107            $inDigits = $workDigits;
108        }
109
110        $result = strrev( $result );
111    }
112
113    if ( !$lowercase ) {
114        $result = strtoupper( $result );
115    }
116
117    return str_pad( $result, $pad, '0', STR_PAD_LEFT );
118}