StateUtil::sanitizeString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 16
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 19
rs 9.7333
1
<?php
2
3
namespace Ipag\Sdk\Util;
4
5
abstract class StateUtil
6
{
7
    private static $states = [
8
        'AC' => 'Acre',
9
        'AL' => 'Alagoas',
10
        'AP' => 'Amapá',
11
        'AM' => 'Amazonas',
12
        'BA' => 'Bahia',
13
        'CE' => 'Ceará',
14
        'DF' => 'Distrito Federal',
15
        'ES' => 'Espírito Santo',
16
        'GO' => 'Goiás',
17
        'MA' => 'Maranhão',
18
        'MT' => 'Mato Grosso',
19
        'MS' => 'Mato Grosso do Sul',
20
        'MG' => 'Minas Gerais',
21
        'PA' => 'Pará',
22
        'PB' => 'Paraíba',
23
        'PR' => 'Paraná',
24
        'PE' => 'Pernambuco',
25
        'PI' => 'Piauí',
26
        'RJ' => 'Rio de Janeiro',
27
        'RN' => 'Rio Grande do Norte',
28
        'RS' => 'Rio Grande do Sul',
29
        'RO' => 'Rondônia',
30
        'RR' => 'Roraima',
31
        'SC' => 'Santa Catarina',
32
        'SP' => 'São Paulo',
33
        'SE' => 'Sergipe',
34
        'TO' => 'Tocantins'
35
    ];
36
37
    public static function transformState(string $state): ?string
38
    {
39
        $state = strtoupper(self::sanitizeString(trim($state)));
40
41
        if (array_key_exists(strtoupper(trim($state)), self::$states)) {
42
            return $state;
43
        }
44
45
        $found =
46
            array_search
47
            (
48
                $state,
49
                array_map(function ($v) {
50
                    return strtoupper(self::sanitizeString($v));
51
                }, self::$states)
52
            );
53
54
        return $found ? $found : null;
55
    }
56
57
    private static function sanitizeString($str)
58
    {
59
        $str = preg_replace('/[áàãâä]/ui', 'a', $str);
60
        $str = preg_replace('/[ÁÀÂÃÄ]/ui', 'A', $str);
61
        $str = preg_replace('/[éèêë]/ui', 'e', $str);
62
        $str = preg_replace('/[ÉÈÊ]/ui', 'E', $str);
63
        $str = preg_replace('/[íìîï]/ui', 'i', $str);
64
        $str = preg_replace('/[ÍÌ]/ui', 'I', $str);
65
        $str = preg_replace('/[óòõôö]/ui', 'o', $str);
66
        $str = preg_replace('/[ÓÒÔÕÖ]/ui', 'O', $str);
67
        $str = preg_replace('/[úùûü]/ui', 'u', $str);
68
        $str = preg_replace('/[ÚÙÜ]/ui', 'U', $str);
69
        $str = preg_replace('/[ç]/ui', 'c', $str);
70
        $str = preg_replace('/[Ç]/ui', 'C', $str);
71
        $str = preg_replace('/[ñ]/ui', 'n', $str);
72
        $str = preg_replace('/[Ñ]/ui', 'N', $str);
73
        $str = preg_replace('/\s/ui', '_', $str);
74
75
        return $str;
76
    }
77
78
}