Aurora Extensions

Logo

Examples, illustrations, UML diagrams, etc.

Token

Table of Contents

Description

Magento provides the Magento\Framework\Math\Random1 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:

The generate method utilizes random_bytes2 for random sequence generation, and the isHex method verifies the given sequence contains only hexidecimal characters.

Usage

...
/** @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

  1. Magento\Framework\Math\Random (GitHub)
  2. random_bytes