Token

  • Published: 2019-08-21

  • Author: Nickolas Burr

Description

Magento provides the Magento\Framework\Math\Random [1] class for generating random data. This class is particularly useful when you need things like tokens, nonces, and salts, and is used in several areas of the framework. However, we’d prefer to have an entirely static class that provides the same functionality, which we can do with PHP builtins.

In the example below, the Token class provides two static methods:

  • generate

  • isHex

The generate method utilizes random_bytes [2] for random sequence generation, and the isHex method verifies the given sequence contains only hexidecimal characters.

Usage

<?php
...
/** @var string $token */
$token = Token::generate();
...

Source

<?php
/**
 * Token.php
 */
declare(strict_types=1);

namespace Vendor\Package\Model\Security;

class Token
{
    /** @constant string REGEX */
    public const REGEX = '/[^a-f0-9]/';

    /**
     * @param int $length
     * @return string
     */
    public static function generate(int $length = 32): string
    {
        return bin2hex(random_bytes($length));
    }

    /**
     * @param string $token
     * @return bool
     */
    public static function isHex(string $token): bool
    {
      return !preg_match(self::REGEX, $token);
    }
}

Notes