Completed
Push — master ( 774d12...7a0ba2 )
by Wanderson
02:14
created

strings.php ➔ strTruncate()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 5
nop 3
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * FUNÇÕES DE TRATAMENTO DE STRINGS
5
 * Funções que tratam uma string e a retorna modificada começam com nome: str[...]
6
 * Funções que convertem uma string para outro formato começam com nome: strTo[...]
7
 * Funções de conversão deve ter o nome no formato:  [...]To[...]
8
 */
9
10
setlocale(LC_ALL, 'pt_BR.UTF8');
11
12
/**
13
 * Corta um texto, sem cortar a última palavra.
14
 * @param string $string [string a ser cortada]
15
 * @param int $length [tamanho da string cortada]
16
 * @param bool $rep  [define se corta antes ou depois do tamanho maximo]
17
 * @return string $string [string resumida ]
18
 */
19
function strTruncate($string, $length, $rep = false) {
20
	if (strlen($string) <= $length) {
21
		return $string;
22
	}
23
24
	if ($rep == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
25
		$oc = strrpos(substr($string, 0, $length), ' ');
26
	}
27
	if ($rep == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
28
		$oc = strpos(substr($string, $length), ' ') + $length;
29
	}
30
31
	$string = substr($string, 0, $oc) . '...';
0 ignored issues
show
Bug introduced by
The variable $oc does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
32
	return $string;
33
}
34
35
/**
36
 * Remove aspas da string (Evita SQL-INJECT)
37
 * @param string $string
38
 * @return string [String sem aspas]
39
 */
40
function strEscape($string) {
41
	if (!get_magic_quotes_gpc()) {
42
		return $string;
43
		/* return mysqli_real_escape_string($string); */
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
44
	} else {
45
		return $string;
46
	}
47
}
48
49
/**
50
 * Limpa a string de caracteres inválidos
51
 * @param string $string
52
 * @return string
53
 */
54
function strClear($string) {
55
	return trim(strip_tags(str_replace('"', '&quot;', $string)));
56
}
57
58
/**
59
 * Criptografa a string utilizando MD5 + SALT
60
 * @param string $string [string a ser criptografada]
61
 * @return string $stringEncript [string criptografada]
62
 */
63
function strEncrypt($string, $salt = APP_ID) {
64
	return md5($salt . $string);
65
}
66
67
/**
68
 * Retorna total de caracteres da string UTF-8
69
 * @param string
70
 * @return int
71
 */
72
function strLength($string) {
73
	return mb_strlen($string);
74
}
75
76
/**
77
 * Retorna a string Maiúscula UTF-8
78
 * @param string $string
79
 * @return string
80
 */
81
function strUpper($string) {
82
	return mb_strtoupper($string);
83
}
84
85
/**
86
 * Retorna a string Minúscula UTF-8
87
 * @param string $string
88
 * @return string
89
 */
90
function strLower($string) {
91
	return mb_strtolower($string);
92
}
93
94
/**
95
 * Retorna a string somente com a primeira letra maiúscula UTF-8
96
 * @param string $string
97
 * @return string
98
 */
99
function strFirst($string) {
100
	return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
101
}
102
103
/**
104
 * Limpa a string, retirando espaços e tags html
105
 * @param string $string
106
 * @return string [retorna string limpa]
107
 */
108
function strStrip($string) {
109
	return trim(strip_tags($string));
110
}
111
112
/**
113
 * Formata o número com zeros à esquerda
114
 * @param int $int [numero a ser formatado]
115
 * @param int $length [quantidade de caracteres que o numero deverá ter]
116
 * @return string [número formatado. Ex: 01, 02 , 001, 003]
117
 */
118
function strLengthFormat($int = 0, $length = 2) {
119
	return str_pad($int, $length, "0", STR_PAD_LEFT);
120
}
121
122
/**
123
 * Converte uma string, nome ou frase em URL válida
124
 * @param string $string  [Ex: Minha Notícia da 'Página 2000 especial' ]
125
 * @return string $url [Ex: minha-noticia-da-pagina-2000-especial ]
126
 */
127
function strToURL($string) {
128
	$url = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
129
	$url = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $url);
130
	$url = strtolower(trim($url, '-'));
131
	$url = preg_replace("/[\/_| -]+/", '-', $url);
132
	return $url;
133
}
134
135
/**
136
 * Converte String para Float
137
 * @param string $string
138
 * @return float
139
 */
140
function strToFloat($string) {
141
	$f = str_replace(array('.', 'R$', '%'), array('', '', ''), $string);
142
	$f2 = str_replace(',', '.', $f);
143
	return (float) ($f2);
144
}
145
146
/**
147
 * Converte float para Moeda (em Real R$)
148
 * @param float $float
149
 * @return string
150
 */
151
function floatToMoney($float) {
152
	return number_format((float) $float, 2, ',', '.');
153
}
154
155
/**
156
 * Converte boolean para String 
157
 * @param boolean $boolean
158
 * @return string (Sim/Não)
159
 */
160
function booleanToString($boolean) {
161
	if ($boolean == true):
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
162
		return 'Sim';
163
	else:
164
		return 'Não';
165
	endif;
166
}
167
168
/**
169
 * Retorna no formato de ID, ex:  #00009 
170
 * @param int
171
 * @return string
172
 */
173
function formatId($id = 0) {
174
	return '#' . strLengthFormat($id, 6);
175
}
176