<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\Twig\Extensions;

use Random\RandomException;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class RandomExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('random_string', $this->randomString(...)),
        ];
    }

    /**
     * @throws RandomException
     */
    public function randomString(int $length = 16): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $result = '';
        $maxIndex = mb_strlen($chars) - 1;

        for ($i = 0; $i < $length; ++$i) {
            $result .= $chars[random_int(0, $maxIndex)];
        }

        return $result;
    }
}
