Created
June 20, 2014 20:20
-
-
Save cameri/d72892d240ef6bbe01bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('Component', 'Controller'); | |
class CodeComponent extends Component { | |
private $letters = array( | |
'6','M','Z','J','L', | |
'K','2','H','R','W', | |
'5','U','3','S','Y', | |
'X','4','7','C','A', | |
'P','F','9','0','1' | |
); | |
public function encode($num) { | |
$t = (int) $num; | |
if ($t < 0) | |
$t = 0; | |
$len = count($this->letters); | |
$code = ''; | |
do { | |
$code = $this->letters[$t % $len] . $code; | |
$t = (int) ($t / $len); | |
} while ($t > 0); | |
return $code; | |
} | |
public function decode($code) { | |
if (empty($code)) { | |
return false; | |
} | |
$num = 0; | |
$len = count($this->letters); | |
$codelen = strlen($code); | |
for ($i=$codelen-1; $i >= 0; $i--) { | |
$index = array_search($code[$i], $this->letters); | |
if ($index === false) | |
return false; | |
$num += $index * pow($len, $codelen-$i-1); | |
} | |
return $num; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment