Completed
Pull Request — 1.0 (#19)
by Vagner Luz do
02:11
created

helpers.php ➔ parse_langs_to_array()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 8
nop 1
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
if (! function_exists('parse_langs_to_array')) {
4
    /**
5
     * Parse a simple string comma-separated to array.
6
     * @see split_srt_to_simple_array.
7
     * @param string|array $str
8
     *
9
     * @return array
10
     */
11
    function parse_langs_to_array($str)
12
    {
13
        if (is_array($str)) {
14
            $languages = $str;
15
        } else {
16
            $languages = split_str_to_simple_array($str);
17
        }
18
19
        /*
20
         * replaces lang-locale to lang-LOCALE syntax
21
         */
22
        foreach ($languages as $alias => $langLocale) {
23
            if (is_numeric($alias) && preg_match('/(-|_)/', $langLocale)) {
24
                list($lang, $locale) = preg_split('/(-|_)/', $langLocale);
25
26
                $newAlias = strtolower($lang).'_'.strtoupper($locale);
27
28
                if (! isset($languages[$newAlias])) {
29
                    $languages[$newAlias] = $langLocale;
30
                }
31
            }
32
        }
33
34
        return $languages;
35
    }
36
}
37
38
if (! function_exists('split_str_to_simple_array')) {
39
    /**
40
     * Parse a simple string comma-separated to array. It also allow to use simple
41
     * indexes, like: "something:awesome, locale:pt-br, country:brazil".
42
     *
43
     * @param string $str
44
     *
45
     * @return array
46
     */
47
    function split_str_to_simple_array($str)
48
    {
49
        $array = [];
50
51
        /* split pairs of comma-separated values into items */
52
        $items = preg_split('/\s*,\s*/', $str);
53
54
        foreach ($items as $item) {
55
            /* split index:value of each pair of items*/
56
            $pairs = preg_split('/\s*(:=|:|=>|=)\s*/', $item);
57
58
            if (count($pairs) == 2) {
59
                $array[$pairs[0]] = $pairs[1];
60
            } else {
61
                $array[] = $pairs[0];
62
            }
63
        }
64
65
        return $array;
66
    }
67
}
68