1<?php
2namespace Hidehalo\Nanoid;
3
4class Core implements CoreInterface
5{
6    /**
7     * @inheritDoc
8     * @see https://github.com/ai/nanoid/blob/master/async/index.browser.js#L4
9     */
10    public function random(GeneratorInterface $generator, $size, $alphabet = CoreInterface::SAFE_SYMBOLS)
11    {
12        $len = strlen($alphabet);
13        $mask = (2 << log($len - 1) / M_LN2) - 1;
14        $step = (int) ceil(1.6 * $mask * $size / $len);
15        $id = '';
16        while (true) {
17            $bytes = $generator->random($step);
18            for ($i = 1; $i <= $step; $i++) {
19                $byte = $bytes[$i] & $mask;
20                if (isset($alphabet[$byte])) {
21                    $id .= $alphabet[$byte];
22                    if (strlen($id) === $size) {
23
24                        return $id;
25                    }
26                }
27            }
28        }
29    }
30}
31