nasrulhazim
12/29/2017 - 4:30 PM

Hashids Wrapper

Hashids Wrapper

<?php

namespace App\Utilities;

use Hashids\Hashids as HashidsUtility;

/**
 * Hashids Service
 */
class Hashids
{
    /**
     * Hashids/Hashids
     * @var \Hashids\Hashids
     */
    protected $hashids;

    public function __construct($salt, $length, $alphabet)
    {
        $this->hashids = new HashidsUtility($salt, $length, $alphabet);
    }

    /**
     * Create an instance of Hashids
     *
     * @return App\Utilites\Hashids
     */
    public static function make($salt, $length, $alphabet)
    {
        return new self($salt, $length, $alphabet);
    }

    /**
     * Encode
     * @param  int    $value
     * @return string
     */
    public function encode(int $value): string
    {
        return $this->hashids->encode($value);
    }

    /**
     * Decode
     * @param  string
     * @return int|null
     */
    public function decode(string $value): int
    {
        $value = $this->hashids->decode($value);

        if (is_array($value)) {
            return $value[0];
        } else {
            return null;
        }
    }
}