Passed
Push — developer ( 02cc9d...259e2e )
by Mariusz
15:28
created

Utils   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 386
Duplicated Lines 0 %

Test Coverage

Coverage 88.89%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 58
eloc 165
dl 0
loc 386
rs 4.5599
c 2
b 0
f 0
ccs 32
cts 36
cp 0.8889

16 Methods

Rating   Name   Duplication   Size   Complexity  
B flattenKeys() 0 27 6
B getLocksContent() 0 26 8
A saveToFile() 0 17 5
A mbUcfirst() 0 3 1
A changeSequence() 0 13 4
A htmlToText() 0 3 1
A flatten() 0 14 5
A merge() 0 14 5
A sanitizeSpecialChars() 0 53 1
A isAssoc() 0 6 2
A getInitials() 0 4 2
A convertCharacterEncoding() 0 8 5
A isHtml() 0 7 3
A varExport() 0 16 5
A detectRecursion() 0 10 4
A getNumberRecordsByModule() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Utils often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Utils, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Utils class.
4
 *
5
 * @package App
6
 *
7
 * @copyright YetiForce S.A.
8
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
9
 * @author    Mariusz Krzaczkowski <[email protected]>
10
 * @author    Radosław Skrzypczak <[email protected]>
11
 */
12
13
namespace App;
14
15
class Utils
16
{
17
	/**
18
	 * Function to capture the initial letters of words.
19
	 *
20
	 * @param string $name
21
	 *
22
	 * @return string
23
	 */
24
	public static function getInitials(string $name): string
25
	{
26
		preg_match_all('#(?<=\s|\b)\pL|[()]#u', $name, $initial);
27
		return isset($initial[0]) ? implode('', $initial[0]) : '';
28
	}
29
30
	/**
31
	 * Outputs or returns a parsable string representation of a variable.
32
	 *
33
	 * @see https://php.net/manual/en/function.var-export.php
34
	 *
35
	 * @param mixed $variable
36 5794
	 *
37
	 * @return mixed the variable representation when the <i>return</i>
38 5794
	 */
39 5794
	public static function varExport($variable)
40 5794
	{
41 5788
		if (\is_array($variable)) {
42 5788
			$toImplode = [];
43
			if (static::isAssoc($variable)) {
44
				foreach ($variable as $key => $value) {
45 5786
					$toImplode[] = var_export($key, true) . '=>' . static::varExport($value);
46 5780
				}
47
			} else {
48
				foreach ($variable as $value) {
49
					$toImplode[] = static::varExport($value);
50 5794
				}
51
			}
52 5788
			return '[' . implode(',', $toImplode) . ']';
53
		}
54
		return var_export($variable, true);
55
	}
56
57
	/**
58
	 * Check if array is associative.
59
	 *
60
	 * @param array $arr
61
	 *
62 5794
	 * @return bool
63
	 */
64 5794
	public static function isAssoc(array $arr)
65 5785
	{
66
		if (empty($arr)) {
67 5788
			return false;
68
		}
69
		return array_keys($arr) !== range(0, \count($arr) - 1);
70
	}
71
72
	/**
73
	 * Flatten a multi-dimensional array into a single level.
74
	 *
75
	 * @param array $array
76
	 * @param float $depth
77
	 *
78
	 * @return array
79 1
	 */
80
	public static function flatten(array $array, float $depth = INF): array
81 1
	{
82 1
		$result = [];
83
		foreach ($array as $item) {
84
			if (\is_array($item)) {
85
				$values = 1 === $depth ? array_values($item) : static::flatten($item, $depth - 1);
86 1
				foreach ($values as $value) {
87
					$result[] = $value;
88
				}
89
			} else {
90
				$result[] = $item;
91
			}
92
		}
93
		return $result;
94
	}
95
96 1
	/**
97
	 * Flatten the multidimensional array on one level, keeping the key names unique.
98 1
	 *
99 1
	 * @param array  $array
100
	 * @param string $type
101
	 * @param float  $depth
102
	 *
103
	 * @return array
104
	 */
105
	public static function flattenKeys(array $array, string $type = '_', float $depth = INF): array
106
	{
107
		$result = [];
108
		foreach ($array as $key => $item) {
109
			if (\is_array($item)) {
110
				if (1 === $depth) {
111
					$values = array_values($item);
112
				} else {
113 19
					$values = static::flattenKeys($item, $type, $depth - 1);
114
				}
115 19
				foreach ($values as $keySec => $value) {
116 1
					switch ($type) {
117
						case 'ucfirst':
118 19
							$keySec = ucfirst($keySec);
119 10
							$newKey = "{$key}{$keySec}";
120
							break;
121 19
						default:
122 1
							$newKey = "{$key}{$type}{$keySec}";
123
							break;
124 19
					}
125
					$result[$newKey] = $value;
126 19
				}
127 19
			} else {
128
				$result[$key] = $item;
129 19
			}
130
		}
131
		return $result;
132
	}
133
134
	/**
135
	 * Merge two arrays.
136
	 *
137
	 * @param array $array1
138
	 * @param array $array2
139
	 *
140
	 * @return array
141
	 */
142
	public static function merge(array $array1, array $array2): array
143
	{
144
		foreach ($array2 as $key => $value) {
145
			if (isset($array1[$key])) {
146
				if (\is_array($array1[$key]) && \is_array($value)) {
147
					$array1[$key] = self::merge($array1[$key], $value);
148
				} else {
149
					$array1[$key] = $value;
150
				}
151
			} else {
152
				$array1[$key] = $value;
153
			}
154
		}
155
		return $array1;
156
	}
157
158
	/**
159
	 * Convert string from encoding to encoding.
160
	 *
161
	 * @param string $value
162
	 * @param string $fromCharset
163
	 * @param string $toCharset
164
	 *
165
	 * @return string
166
	 */
167
	public static function convertCharacterEncoding($value, $fromCharset, $toCharset)
168
	{
169
		if (\function_exists('mb_convert_encoding') && \function_exists('mb_list_encodings') && \in_array($fromCharset, mb_list_encodings()) && \in_array($toCharset, mb_list_encodings())) {
170
			$value = mb_convert_encoding($value, $toCharset, $fromCharset);
171
		} else {
172
			$value = iconv($fromCharset, $toCharset, $value);
173
		}
174
		return $value;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $value also could return the type array which is incompatible with the documented return type string.
Loading history...
175
	}
176
177
	/**
178
	 * Function to check is a html message.
179
	 *
180
	 * @param string $content
181
	 *
182
	 * @return bool
183
	 */
184
	public static function isHtml(string $content): bool
185
	{
186
		$content = trim($content);
187
		if ('<' === substr($content, 0, 1) && '>' === substr($content, -1)) {
188
			return true;
189
		}
190
		return $content != strip_tags($content);
191
	}
192
193
	/**
194
	 * Strip tags content.
195
	 *
196
	 * @param string $content
197
	 *
198
	 * @return string
199
	 */
200
	public static function htmlToText(string $content): string
201
	{
202
		return trim(preg_replace('/[ \t\n]+/', ' ', strip_tags($content)));
203
	}
204
205
	/**
206
	 * Function to save php file with cleaning file cache.
207
	 *
208
	 * @param string       $pathDirectory
209
	 * @param array|string $content
210
	 * @param string       $comment
211
	 * @param int          $flag
212
	 * @param bool         $return
213
	 *
214
	 * @return bool $value
215
	 */
216
	public static function saveToFile(string $pathDirectory, $content, string $comment = '', int $flag = LOCK_EX, bool $return = false): bool
217
	{
218
		if (\is_array($content)) {
219
			$content = self::varExport($content);
220
		}
221
		if ($return) {
222
			$content = "return $content;";
223
		}
224
		if ($comment) {
225
			$content = "<?php \n/**  {$comment}  */\n{$content}\n";
226
		} else {
227
			$content = "<?php $content" . PHP_EOL;
228
		}
229
		if (false !== $value = file_put_contents($pathDirectory, $content, $flag)) {
230
			Cache::resetFileCache($pathDirectory);
231
		}
232
		return (bool) $value;
233
	}
234
235
	/**
236
	 * Replacement for the ucfirst function for proper Multibyte String operation.
237
	 * Delete function will exist as mb_ucfirst.
238
	 *
239
	 * @param string $string
240
	 *
241
	 * @return string
242
	 */
243
	public static function mbUcfirst($string)
244
	{
245
		return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
246
	}
247
248
	/**
249
	 * Sanitize special chars from given string.
250
	 *
251
	 * @param string $string
252
	 * @param string $delimiter
253
	 *
254
	 * @return string
255
	 */
256
	public static function sanitizeSpecialChars(string $string, string $delimiter = '_'): string
257
	{
258
		$string = mb_convert_encoding((string) $string, 'UTF-8', mb_list_encodings());
259
		$replace = [
260
			'ъ' => '-', 'Ь' => '-', 'Ъ' => '-', 'ь' => '-',
261
			'Ă' => 'A', 'Ą' => 'A', 'À' => 'A', 'Ã' => 'A', 'Á' => 'A', 'Æ' => 'A', 'Â' => 'A', 'Å' => 'A', 'Ä' => 'Ae',
262
			'Þ' => 'B', 'Ć' => 'C', 'ץ' => 'C', 'Ç' => 'C', 'È' => 'E', 'Ę' => 'E', 'É' => 'E', 'Ë' => 'E', 'Ê' => 'E',
263
			'Ğ' => 'G', 'İ' => 'I', 'Ï' => 'I', 'Î' => 'I', 'Í' => 'I', 'Ì' => 'I', 'Ł' => 'L', 'Ñ' => 'N', 'Ń' => 'N',
264
			'Ø' => 'O', 'Ó' => 'O', 'Ò' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'Oe', 'Ş' => 'S', 'Ś' => 'S', 'Ș' => 'S',
265
			'Š' => 'S', 'Ț' => 'T', 'Ù' => 'U', 'Û' => 'U', 'Ú' => 'U', 'Ü' => 'Ue', 'Ý' => 'Y', 'Ź' => 'Z', 'Ž' => 'Z',
266
			'Ż' => 'Z', 'â' => 'a', 'ǎ' => 'a', 'ą' => 'a', 'á' => 'a', 'ă' => 'a', 'ã' => 'a', 'Ǎ' => 'a', 'а' => 'a',
267
			'А' => 'a', 'å' => 'a', 'à' => 'a', 'א' => 'a', 'Ǻ' => 'a', 'Ā' => 'a', 'ǻ' => 'a', 'ā' => 'a', 'ä' => 'ae',
268
			'æ' => 'ae', 'Ǽ' => 'ae', 'ǽ' => 'ae',	'б' => 'b', 'ב' => 'b', 'Б' => 'b', 'þ' => 'b',	'ĉ' => 'c', 'Ĉ' => 'c',
269
			'Ċ' => 'c', 'ć' => 'c', 'ç' => 'c', 'ц' => 'c', 'צ' => 'c', 'ċ' => 'c', 'Ц' => 'c', 'Č' => 'c', 'č' => 'c',
270
			'Ч' => 'ch', 'ч' => 'ch', 'ד' => 'd', 'ď' => 'd', 'Đ' => 'd', 'Ď' => 'd', 'đ' => 'd', 'д' => 'd', 'Д' => 'D',
271
			'ð' => 'd', 'є' => 'e', 'ע' => 'e', 'е' => 'e', 'Е' => 'e', 'Ə' => 'e', 'ę' => 'e', 'ĕ' => 'e', 'ē' => 'e',
272
			'Ē' => 'e', 'Ė' => 'e', 'ė' => 'e', 'ě' => 'e', 'Ě' => 'e', 'Є' => 'e', 'Ĕ' => 'e', 'ê' => 'e', 'ə' => 'e',
273
			'è' => 'e', 'ë' => 'e', 'é' => 'e', 'ф' => 'f', 'ƒ' => 'f', 'Ф' => 'f', 'ġ' => 'g', 'Ģ' => 'g', 'Ġ' => 'g',
274
			'Ĝ' => 'g', 'Г' => 'g', 'г' => 'g', 'ĝ' => 'g', 'ğ' => 'g', 'ג' => 'g', 'Ґ' => 'g', 'ґ' => 'g', 'ģ' => 'g',
275
			'ח' => 'h', 'ħ' => 'h', 'Х' => 'h', 'Ħ' => 'h', 'Ĥ' => 'h', 'ĥ' => 'h', 'х' => 'h', 'ה' => 'h', 'î' => 'i',
276
			'ï' => 'i', 'í' => 'i', 'ì' => 'i', 'į' => 'i', 'ĭ' => 'i', 'ı' => 'i', 'Ĭ' => 'i', 'И' => 'i', 'ĩ' => 'i',
277
			'ǐ' => 'i', 'Ĩ' => 'i', 'Ǐ' => 'i', 'и' => 'i', 'Į' => 'i', 'י' => 'i', 'Ї' => 'i', 'Ī' => 'i', 'І' => 'i',
278
			'ї' => 'i', 'і' => 'i', 'ī' => 'i', 'ij' => 'ij', 'IJ' => 'ij', 'й' => 'j', 'Й' => 'j', 'Ĵ' => 'j', 'ĵ' => 'j',
279
			'я' => 'ja', 'Я' => 'ja', 'Э' => 'je', 'э' => 'je', 'ё' => 'jo', 'Ё' => 'jo', 'ю' => 'ju', 'Ю' => 'ju',
280
			'ĸ' => 'k', 'כ' => 'k', 'Ķ' => 'k', 'К' => 'k', 'к' => 'k', 'ķ' => 'k', 'ך' => 'k', 'Ŀ' => 'l', 'ŀ' => 'l',
281
			'Л' => 'l', 'ł' => 'l', 'ļ' => 'l', 'ĺ' => 'l', 'Ĺ' => 'l', 'Ļ' => 'l', 'л' => 'l', 'Ľ' => 'l', 'ľ' => 'l',
282
			'ל' => 'l', 'מ' => 'm', 'М' => 'm', 'ם' => 'm', 'м' => 'm', 'ñ' => 'n', 'н' => 'n', 'Ņ' => 'n', 'ן' => 'n',
283
			'ŋ' => 'n', 'נ' => 'n', 'Н' => 'n', 'ń' => 'n', 'Ŋ' => 'n', 'ņ' => 'n', 'ʼn' => 'n', 'Ň' => 'n', 'ň' => 'n',
284
			'о' => 'o', 'О' => 'o', 'ő' => 'o', 'õ' => 'o', 'ô' => 'o', 'Ő' => 'o', 'ŏ' => 'o', 'Ŏ' => 'o', 'Ō' => 'o',
285
			'ō' => 'o', 'ø' => 'o', 'ǿ' => 'o', 'ǒ' => 'o', 'ò' => 'o', 'Ǿ' => 'o', 'Ǒ' => 'o', 'ơ' => 'o', 'ó' => 'o',
286
			'Ơ' => 'o', 'œ' => 'oe', 'Œ' => 'oe', 'ö' => 'oe', 'פ' => 'p', 'ף' => 'p', 'п' => 'p', 'П' => 'p', 'ק' => 'q',
287
			'ŕ' => 'r', 'ř' => 'r', 'Ř' => 'r', 'ŗ' => 'r', 'Ŗ' => 'r', 'ר' => 'r', 'Ŕ' => 'r', 'Р' => 'r', 'р' => 'r',
288
			'ș' => 's', 'с' => 's', 'Ŝ' => 's', 'š' => 's', 'ś' => 's', 'ס' => 's', 'ş' => 's', 'С' => 's', 'ŝ' => 's',
289
			'Щ' => 'sch', 'щ' => 'sch', 'ш' => 'sh', 'Ш' => 'sh', 'ß' => 'ss', 'т' => 't', 'ט' => 't', 'ŧ' => 't',
290
			'ת' => 't', 'ť' => 't', 'ţ' => 't', 'Ţ' => 't', 'Т' => 't', 'ț' => 't', 'Ŧ' => 't', 'Ť' => 't', '™' => 'tm',
291
			'ū' => 'u', 'у' => 'u', 'Ũ' => 'u', 'ũ' => 'u', 'Ư' => 'u', 'ư' => 'u', 'Ū' => 'u', 'Ǔ' => 'u', 'ų' => 'u',
292
			'Ų' => 'u', 'ŭ' => 'u', 'Ŭ' => 'u', 'Ů' => 'u', 'ů' => 'u', 'ű' => 'u', 'Ű' => 'u', 'Ǖ' => 'u', 'ǔ' => 'u',
293
			'Ǜ' => 'u', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'У' => 'u', 'ǚ' => 'u', 'ǜ' => 'u', 'Ǚ' => 'u', 'Ǘ' => 'u',
294
			'ǖ' => 'u', 'ǘ' => 'u', 'ü' => 'ue', 'в' => 'v', 'ו' => 'v', 'В' => 'v', 'ש' => 'w', 'ŵ' => 'w', 'Ŵ' => 'w',
295
			'ы' => 'y', 'ŷ' => 'y', 'ý' => 'y', 'ÿ' => 'y', 'Ÿ' => 'y', 'Ŷ' => 'y', 'Ы' => 'y', 'ž' => 'z', 'З' => 'z',
296
			'з' => 'z', 'ź' => 'z', 'ז' => 'z', 'ż' => 'z', 'ſ' => 'z', 'Ж' => 'zh', 'ж' => 'zh', 'Ð' => 'D', 'Θ' => '8',
297
			'©' => '(c)', 'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Ι' => 'I',
298
			'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',	'Ρ' => 'R', 'Σ' => 'S',
299
			'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W', 'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I',
300
			'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I', 'Ϋ' => 'Y', 'α' => 'a', 'β' => 'b', 'γ' => 'g',
301
			'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8', 'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm',
302
			'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p', 'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f',
303
			'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w', 'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h',
304
			'ώ' => 'w', 'ς' => 's', 'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
305
		];
306
		$string = strtr($string, $replace);
307
		$string = preg_replace('/[^\p{L}\p{Nd}\.]+/u', $delimiter, $string);
308
		return trim($string, $delimiter);
309
	}
310
311
	/**
312
	 * Change the order of associative array.
313
	 *
314
	 * @param array $array
315
	 * @param array $order
316
	 *
317
	 * @return array
318
	 */
319
	public static function changeSequence(array $array, array $order): array
320
	{
321
		if (!$order) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $order of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
322
			return $array;
323
		}
324
		$returnLinks = [];
325
		foreach ($order as $value) {
326
			if ($array[$value]) {
327
				$returnLinks[$value] = $array[$value];
328
			}
329
			unset($array[$value]);
330
		}
331
		return array_merge($returnLinks, $array);
332
	}
333
334
	/**
335
	 * Get locks content by events.
336
	 *
337
	 * @param array $locks
338
	 *
339
	 * @return string
340
	 */
341
	public static function getLocksContent(array $locks): string
342
	{
343
		$return = '';
344
		foreach ($locks as $lock) {
345
			switch ($lock) {
346
				case 'copy':
347
					$return .= ' oncopy = "return false"';
348
					break;
349
				case 'cut':
350
					$return .= ' oncut = "return false"';
351
					break;
352
				case 'paste':
353
					$return .= ' onpaste = "return false"';
354
					break;
355
				case 'contextmenu':
356
					$return .= ' oncontextmenu = "return false"';
357
					break;
358
				case 'selectstart':
359
					$return .= ' onselectstart = "return false" onselect = "return false"';
360
					break;
361
				case 'drag':
362
					$return .= ' ondragstart = "return false" ondrag = "return false"';
363
					break;
364
			}
365
		}
366
		return $return;
367
	}
368
369
	/**
370
	 * Detect recursion / circular references.
371
	 * Recommend not using this feature as it will be removed in the future.
372
	 *
373
	 * @param string $class
374
	 * @param string $function
375
	 * @param int    $limit
376
	 *
377
	 * @return bool
378
	 */
379
	public static function detectRecursion(string $class, string $function, int $limit = 1): bool
380
	{
381
		$counter = 0;
382
		foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) as $trace) {
383
			$counter += (int) ($class === ($trace['class'] ?? '') && $function === $trace['function']);
384
			if ($counter > $limit) {
385
				break;
386
			}
387
		}
388
		return $counter > $limit;
389
	}
390
391
	/**
392
	 * Get the number of records by modules.
393
	 *
394
	 * @return array
395
	 */
396
	public static function getNumberRecordsByModule(): array
397
	{
398
		return (new \App\Db\Query())->select(['setype', 'counter' => new \yii\db\Expression('count(setype)')])->from('vtiger_crmentity')
399
			->groupBy('setype')->orderBy(['counter' => SORT_DESC])
400
			->createCommand()->queryAllByGroup();
401
	}
402
}
403