<?php
class Integer
{
static protected $alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
static protected $base = 62;
static public function setAlphabet( $alphabet )
{
if ( !is_string($alphabet) )
{
throw new Exception('Given alphabet is not a string !');
}
self::$base = strlen( $alphabet );
if ( strlen( count_chars( $alphabet, 3 ) ) != self::$base )
{
throw new Exception('The following alphabet has doubled characters : '.$alphabet);
}
self::$alphabet = $alphabet;
}
static public function getAlphabet() { return self::$alphabet; }
static public function getBase() { return self::$base; }
static public function encode( $integer )
{
$integer = (int)$integer;
if ( $integer < 0 )
{
return false;
}
$string = '';
while( $integer )
{
$pos = $integer % self::$base;
$string .= self::$alphabet[ $pos ];
$integer = ( $integer - $pos ) / self::$base;
}
return strrev( $string );
}
static public function decode( $string )
{
$string = (string)$string;
if ( strcspn( $string, self::$alphabet ) )
{
return false;
}
$integer = 0;
$unit = 1;
for( $i = strlen( $string ) -1; $i >= 0; $i -- )
{
$pos = strpos( self::$alphabet, $string[$i] );
$integer += $pos * $unit;
$unit = $unit * self::$base;
}
return $integer;
}
}