RandomHelper::getRandomChar()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the TheAlternativeZurich/events project.
5
 *
6
 * (c) Florian Moser <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace App\Helper;
13
14
class RandomHelper
15
{
16
    /**
17
     * @return bool|string
18
     */
19
    public static function generateHumanReadableRandom(int $minimalLength, string $divider)
20
    {
21
        $vocals = 'aeiou';
22
        $vocalsLength = mb_strlen($vocals);
23
24
        //skip because ambiguous: ck, jyi
25
        $normals = 'bdfghklmnpqrstvwxz';
26
        $normalsLength = mb_strlen($normals);
27
28
        $randomString = '';
29
        $length = 0;
30
        do {
31
            if ($length > 0) {
32
                $randomString .= $divider;
33
                ++$length;
34
            }
35
36
            // create bigger group
37
            $randomString .= self::getRandomChar($normals, $normalsLength);
38
            $randomString .= self::getRandomChar($vocals, $vocalsLength);
39
            $randomString .= self::getRandomChar($normals, $normalsLength);
40
            $length += 3;
41
42
            // abort if too big already
43
            if ($length > $minimalLength) {
44
                break;
45
            }
46
47
            // create smaller group
48
            $randomString .= $divider;
49
            $randomString .= self::getRandomChar($normals, $normalsLength);
50
            $randomString .= self::getRandomChar($vocals, $vocalsLength);
51
            $length += 3;
52
        } while ($length < $minimalLength);
53
54
        return $randomString;
55
    }
56
57
    /**
58
     * @return bool|string
59
     */
60
    private static function getRandomChar(string $selection, int $selectionLength)
61
    {
62
        $entry = rand(0, $selectionLength - 1);
63
64
        return mb_substr($selection, $entry, 1);
65
    }
66
}
67