Base62.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Codec;
  12. use Hyperf\Codec\Exception\InvalidArgumentException;
  13. class Base62
  14. {
  15. public const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  16. public const BASE = 62;
  17. public static function encode(int $number): string
  18. {
  19. $chars = [];
  20. while ($number > 0) {
  21. $remain = $number % static::BASE;
  22. $chars[] = static::CHARS[$remain];
  23. $number = ($number - $remain) / static::BASE;
  24. }
  25. return implode('', array_reverse($chars));
  26. }
  27. public static function decode(string $data): int
  28. {
  29. if ($data === '' || strlen($data) !== strspn($data, self::CHARS)) {
  30. throw new InvalidArgumentException('The decode data contains content outside of CHARS.');
  31. }
  32. return array_reduce(array_map(function ($character) {
  33. return strpos(static::CHARS, $character);
  34. }, str_split($data)), function ($result, $remain) {
  35. return $result * static::BASE + $remain;
  36. });
  37. }
  38. }