Test Failed
Push — master ( c15d53...e7a44f )
by Roberto
02:16
created

Strings::equilizeParameters()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 10
cp 0
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 3
crap 30
1
<?php
2
3
namespace NFePHP\Common;
4
5
/**
6
 * Classe auxiliar para o tratamento de strings
7
 * @category   NFePHP
8
 * @package    NFePHP\Common\Strings
9
 * @copyright  Copyright (c) 2008-2017
10
 * @license    http://www.gnu.org/licenses/lesser.html LGPL v3
11
 * @author     Roberto L. Machado <linux dot rlm at gmail dot com>
12
 * @link       http://github.com/nfephp-org/nfephp for the canonical source repository
13
 */
14
15
use ForceUTF8\Encoding;
16
17
class Strings
18
{
19
    
20
    /**
21
     * Includes missing or unsupported properties in stdClass inputs
22
     * and Replace all unsuported chars
23
     *
24
     * @param \stdClass $std
25
     * @param array $possible
26
     * @return \stdClass
27
     */
28
    public static function equilizeParameters(
29
        \stdClass $std,
30
        $possible,
31
        $replaceAccentedChars = false
32
    ) {
33
        $arr = get_object_vars($std);
34
        foreach ($possible as $key) {
35
            if (!array_key_exists($key, $arr)) {
36
                $std->$key = null;
37
            } else {
38
                if (is_string($std->$key)) {
39
                    $std->$key = trim(self::replaceUnacceptableCharacters($std->$key));
40
                    if ($replaceAccentedChars) {
41
                        $std->$key = self::toASCII($std->$key);
42
                    }
43
                }
44
            }
45
        }
46
        return $std;
47
    }
48
49
    /**
50
     * Replace all specials characters from string and retuns only 128 basics
51
     * NOTE: only for UTF-8
52
     * @param string $string
53
     * @return  string
54
     */
55 1
    public static function replaceSpecialsChars($string)
56
    {
57 1
        $string = self::squashCharacters($string);
58 1
        $string = str_replace('&', 'e', $string);
59 1
        $string = preg_replace("/[^a-zA-Z0-9 @#,-_.;:$%\/]/", "", $string);
60 1
        return preg_replace("/[<>]/", "", $string);
61
    }
62
    
63
    /**
64
     * Clear inputs for build in XML
65
     * Only UTF-8 characters is acceptable
66
     * & isolated, less than, greater than, quotation marks and apostrophes
67
     * should be replaced by their html equivalent
68
     * Carriage Return, Tab and Line Feed is not acceptable in strings
69
     * Multiple spaces is not acceptable in strings
70
     * And no other control character is acceptable either
71
     * @param string|null $input
72
     * @return string|null
73
     */
74 1
    public static function replaceUnacceptableCharacters($input)
75
    {
76 1
        if (empty($input)) {
77
            return $input;
78
        }
79 1
        $input = str_replace('&', ' & ', $input);
80 1
        $input = str_replace("'", '', $input);
81 1
        $input = preg_replace('/(?:\s\s+)/', ' ', $input);
82
        //& isolated, less than, greater than, quotation marks and apostrophes
83
        //should be replaced by their html equivalent
84 1
        $input = str_replace(
85 1
            ['& ','<','>','"',"'"],
86 1
            ['&amp; ','&lt; ','&gt; ','&quot; ','&#39; '],
87
            $input
88
        );
89 1
        $input = self::normalize($input);
90 1
        return trim($input);
91
    }
92
    
93
    /**
94
     * Converts all UTF-8 remains in ASCII
95
     * @param string $input
96
     * @return string
97
     */
98
    public static function toASCII($input)
99
    {
100
        $input = self::normalize($input);
101
        $input = self::squashCharacters($input);
102
        return mb_convert_encoding($input, 'ascii');
103
    }
104
    
105
    /**
106
     * Replaces all accented characters of their ASCII equivalents
107
     * @param string $input
108
     * @return string
109
     */
110 1
    public static function squashCharacters($input)
111
    {
112 1
        $input = trim($input);
113 1
        $aFind = ['á','à','ã','â','é','ê','í','ó','ô','õ','ö','ú','ü',
114
            'ç','Á','À','Ã','Â','É','Ê','Í','Ó','Ô','Õ','Ö','Ú','Ü','Ç'];
115 1
        $aSubs = ['a','a','a','a','e','e','i','o','o','o','o','u','u',
116
            'c','A','A','A','A','E','E','I','O','O','O','O','U','U','C'];
117 1
        return str_replace($aFind, $aSubs, $input);
118
    }
119
    
120
    /**
121
     * Replace all non-UTF-8 chars to UTF-8
122
     * Remove all control chars
123
     * Remove all multiple spaces
124
     * @param string $input
125
     * @return string
126
     */
127 1
    public static function normalize($input)
128
    {
129
        //Carriage Return, Tab and Line Feed is not acceptable in strings
130 1
        $input = str_replace(["\r","\t","\n"], "", $input);
131
        //Multiple spaces is not acceptable in strings
132 1
        $input = preg_replace('/(?:\s\s+)/', ' ', $input);
133
        //Only UTF-8 characters is acceptable
134 1
        $input = Encoding::fixUTF8($input);
135 1
        $input = preg_replace(
136
            '/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]'.
137
            '|[\x00-\x7F][\x80-\xBF]+'.
138
            '|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*'.
139
            '|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})'.
140 1
            '|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
141 1
            '',
142
            $input
143
        );
144 1
        $input = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]'.
145 1
            '|\xED[\xA0-\xBF][\x80-\xBF]/S', '', $input);
146
        //And no other control character is acceptable either
147 1
        return preg_replace('/[[:cntrl:]]/', '', $input);
148
    }
149
150
    /**
151
     * Remove all non numeric characters from string
152
     * @param string $string
153
     * @return string
154
     */
155 1
    public static function onlyNumbers($string)
156
    {
157 1
        return preg_replace("/[^0-9]/", "", $string);
158
    }
159
    
160
    /**
161
     * Remove unwanted attributes, prefixes, sulfixes and other control
162
     * characters like \r \n \s \t
163
     * @param string $string
164
     * @param boolean $removeEncodingTag remove encoding tag from a xml
165
     * @return string
166
     */
167 2
    public static function clearXmlString($string, $removeEncodingTag = false)
168
    {
169
        $aFind = array(
170 2
            'xmlns:default="http://www.w3.org/2000/09/xmldsig#"',
171
            ' standalone="no"',
172
            'default:',
173
            ':default',
174
            "\n",
175
            "\r",
176
            "\t"
177
        );
178 2
        $retXml = str_replace($aFind, "", $string);
179 2
        $retXml = preg_replace('/(\>)\s*(\<)/m', '$1$2', $retXml);
180 2
        if ($removeEncodingTag) {
181 1
            $retXml = self::deleteAllBetween($retXml, '<?xml', '?>');
182
        }
183 2
        return $retXml;
184
    }
185
    
186
    /**
187
     * Remove all characters between markers
188
     * @param string $string
189
     * @param string $beginning
190
     * @param string $end
191
     * @return string
192
     */
193 2
    public static function deleteAllBetween($string, $beginning, $end)
194
    {
195 2
        $beginningPos = strpos($string, $beginning);
196 2
        $endPos = strpos($string, $end);
197 2
        if ($beginningPos === false || $endPos === false) {
198
            return $string;
199
        }
200 2
        $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
201 2
        return str_replace($textToDelete, '', $string);
202
    }
203
    
204
    /**
205
     * Clears the xml after adding the protocol, removing repeated namespaces
206
     * @param string $string
207
     * @return string
208
     */
209 1
    public static function clearProtocoledXML($string)
210
    {
211 1
        $procXML = self::clearXmlString($string);
212 1
        $aApp = array('nfe','cte','mdfe');
213 1
        foreach ($aApp as $app) {
214 1
            $procXML = str_replace(
215 1
                'xmlns="http://www.portalfiscal.inf.br/'.$app.'" xmlns="http://www.w3.org/2000/09/xmldsig#"',
216 1
                'xmlns="http://www.portalfiscal.inf.br/'.$app.'"',
217
                $procXML
218
            );
219
        }
220 1
        return $procXML;
221
    }
222
    
223
    /**
224
     * Remove some alien chars from txt
225
     * @param string $txt
226
     * @return string
227
     */
228 1
    public static function removeSomeAlienCharsfromTxt($txt)
229
    {
230
        //remove CRs and TABs
231 1
        $txt = str_replace(["\r","\t"], "", $txt);
232
        //remove multiple spaces
233 1
        $txt = preg_replace('/(?:\s\s+)/', ' ', $txt);
234
        //remove spaces at begin and end of fields
235 1
        $txt = str_replace(["| "," |"], "|", $txt);
236 1
        return $txt;
237
    }
238
    
239
    /**
240
     * Creates a string ramdomically with the specified length
241
     * @param int $length
242
     * @return string
243
     */
244 1
    public static function randomString($length)
245
    {
246
        $keyspace = '0123456789abcdefghijklmnopqr'
247 1
            . 'stuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
248 1
        $str = '';
249 1
        $max = mb_strlen($keyspace, '8bit') - 1;
250 1
        for ($i = 0; $i < $length; ++$i) {
251 1
            $str .= $keyspace[rand(0, $max)];
252
        }
253 1
        return $str;
254
    }
255
}
256