/
BaseEncoder.php
86 lines (70 loc) · 2.18 KB
/
BaseEncoder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/*
* This file is part of the Base62 package
*
* Copyright (c) 2016-2018 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/base62
*
*/
namespace Tuupola\Base62;
use InvalidArgumentException;
use Tuupola\Base62;
abstract class BaseEncoder
{
private $options = [
"characters" => Base62::GMP,
];
public function __construct($options = [])
{
$this->options = array_merge($this->options, (array) $options);
}
public function encode($data, $integer = false)
{
if (is_integer($data) || true === $integer) {
$data = [$data];
} else {
$data = str_split($data);
$data = array_map(function ($character) {
return ord($character);
}, $data);
}
$converted = $this->baseConvert($data, 256, 62);
return implode("", array_map(function ($index) {
return $this->options["characters"][$index];
}, $converted));
}
public function decode($data, $integer = false)
{
// If the data contains characters that aren't in the character set
if (strlen($data) !== strspn($data, $this->options["characters"])) {
throw new InvalidArgumentException("Data contains invalid characters");
}
$data = str_split($data);
$data = array_map(function ($character) {
return strpos($this->options["characters"], $character);
}, $data);
/* Return as integer when requested. */
if ($integer) {
$converted = $this->baseConvert($data, 62, 10);
return (integer) implode("", $converted);
}
$converted = $this->baseConvert($data, 62, 256);
return implode("", array_map(function ($ascii) {
return chr($ascii);
}, $converted));
}
public function encodeInteger($data)
{
return $this->encode($data, true);
}
public function decodeInteger($data)
{
return $this->decode($data, true);
}
abstract public function baseConvert(array $source, $source_base, $target_base);
}