IdentifierHelper   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
eloc 17
c 1
b 0
f 1
dl 0
loc 36
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B getHumanReadableIdentifier() 0 28 8
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 IdentifierHelper
15
{
16
    /**
17
     * transforms text to human readable URL
18
     * only outputs lowercase alphanummeric string, invalid characters are replaced by -.
19
     *
20
     * min length 10, max length 100
21
     */
22
    public static function getHumanReadableIdentifier(string $text): string
23
    {
24
        $lowercase = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $text));
25
26
        $result = '';
27
        for ($i = 0; $i < strlen($lowercase); ++$i) {
28
            $character = $lowercase[$i];
29
            $characterValue = ord($character);
30
31
            //0-9, a-z
32
            if (($characterValue >= 48 && $characterValue <= 57) ||
33
                ($characterValue >= 97 && $characterValue <= 122)) {
34
                $result .= $character;
35
            } else {
36
                $result .= '-';
37
            }
38
        }
39
40
        if (strlen($result) > 100) {
41
            $result = substr($result, 0, 100); // make max length
42
            $result = substr($result, 0, strrpos($result, '-')); // cut off last word
43
        }
44
45
        if (strlen($result) < 10) {
46
            $result .= RandomHelper::generateHumanReadableRandom(10, '-');
47
        }
48
49
        return trim($result);
50
    }
51
}
52