VariableUtils::getNextAvailableVariableName()   C
last analyzed

Complexity

Conditions 7
Paths 2

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 32
rs 6.7272
cc 7
eloc 20
nc 2
nop 2
1
<?php
2
3
namespace TheCodingMachine\Yaco\Definition;
4
5
class VariableUtils
6
{
7
    /**
8
     * Returns the next available variable name to use.
9
     *
10
     * @param string $variable      The variable name we wish to use
11
     * @param array  $usedVariables The list of variable names already used.
12
     *
13
     * @return string
14
     */
15
    public static function getNextAvailableVariableName($variable, array $usedVariables)
16
    {
17
        $variable = self::toVariableName($variable);
18
        while (true) {
19
            // check that the name is not reserved
20
            if (!in_array($variable, $usedVariables, true)) {
21
                break;
22
            }
23
24
            $numbers = '';
25
            while (true) {
26
                $lastCharacter = substr($variable, strlen($variable) - 1);
27
                if ($lastCharacter >= '0' && $lastCharacter <= '9') {
28
                    $numbers = $lastCharacter.$numbers;
29
                    $variable = substr($variable, 0, strlen($variable) - 1);
30
                } else {
31
                    break;
32
                }
33
            }
34
35
            if ($numbers === '') {
36
                $numbers = 0;
37
            } else {
38
                $numbers = (int) $numbers;
39
            }
40
            ++$numbers;
41
42
            $variable = $variable.$numbers;
43
        }
44
45
        return $variable;
46
    }
47
48
    /**
49
     * Transform $name into a valid variable name by removing not authorized characters or adding new ones.
50
     *
51
     * - foo => $foo
52
     * - $foo => $foo
53
     * - fo$o => $foo
54
     *
55
     * @param string $name
56
     *
57
     * @return string
58
     */
59
    private static function toVariableName($name)
60
    {
61
        $variableName = preg_replace('/[^A-Za-z0-9]/', '', $name);
62
        if ($variableName{0} >= '0' && $variableName{0} <= '9') {
63
            $variableName = 'a'.$variableName;
64
        }
65
66
        return '$'.$variableName;
67
    }
68
}
69