Url shortening demo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

42 lines
873 B

<?php
declare(strict_types=1);
namespace App;
use App\Exception\InvalidHashException;
use Hashids\Hashids;
use Hashids\HashidsInterface;
class Hasher
{
private HashidsInterface $hashids;
public function __construct(?string $salt = null)
{
$salt = $salt ?? 'default_salt';
$this->hashids = new Hashids($salt, 11);
}
public function encode(int $id): string
{
return $this->hashids->encode($id);
}
/**
* @throws InvalidHashException
*/
public function decode(string $hash): int
{
$decoded = $this->hashids->decode($hash);
if (count($decoded) === 0) {
throw new InvalidHashException('Hash not valid');
}
return $decoded[0];
}
public function isValid(string $hash): bool
{
return count($this->hashids->decode($hash)) !== 0;
}
}