Skip to content
Code-Schnipsel Gruppen Projekte
SimpleString.php 1,04 KiB
Newer Older
Patrick Müller's avatar
Patrick Müller committed
<?php

/**
 * This file contains QUI\ERP\Coupons\CodeGenerators\SimpleString
 */

Patrick Müller's avatar
Patrick Müller committed
namespace QUI\ERP\Coupons\CodeGenerators;

use QUI\ERP\Coupons\CodeGeneratorInterface;
use QUI\ERP\Coupons\Handler;
Patrick Müller's avatar
Patrick Müller committed

use function array_merge;
use function random_int;
use function range;

/**
 * Class SimpleString
 *
 * @package QUI\ERP\Coupons\CodeGenerators
 */
Patrick Müller's avatar
Patrick Müller committed
class SimpleString implements CodeGeneratorInterface
{
    const CODE_LENGTH = 8;

    /**
     * Generate a random, unique Invite code
     *
     * @param string $prefix (optional)
     * @return string
Patrick Müller's avatar
Patrick Müller committed
     */
    public static function generate(string $prefix = ''): string
Patrick Müller's avatar
Patrick Müller committed
    {
        $characters = array_merge(
            range('A', 'Z'),
            range(0, 9)
Patrick Müller's avatar
Patrick Müller committed
        );

        $count = count($characters) - 1;

        do {
            $code = $prefix;

            for ($i = 0; $i < self::CODE_LENGTH; $i++) {
                $code .= $characters[random_int(0, $count)];
Patrick Müller's avatar
Patrick Müller committed
            }
        } while (Handler::existsCode($code));

        return $code;
    }
}