Passed
Push — develop ( bec712...61862d )
by Andrea
15:22
created

ArrayUtils   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Test Coverage

Coverage 91.11%

Importance

Changes 0
Metric Value
eloc 88
dl 0
loc 218
ccs 82
cts 90
cp 0.9111
rs 9.0399
c 0
b 0
f 0
wmc 42

8 Methods

Rating   Name   Duplication   Size   Complexity  
B inMultiarrayTutti() 0 20 8
A executeSortMultiAssociativeArray() 0 8 2
A multiInMultiarray() 0 31 6
B inMultiarray() 0 17 7
A arrayOrderby() 0 16 4
B sortMultiAssociativeArray() 0 27 8
A isSortArray() 0 15 4
A arraySearchRecursive() 0 9 3

How to fix   Complexity   

Complex Class

Complex classes like ArrayUtils 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 ArrayUtils, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Cdf\BiCoreBundle\Utils\Arrays;
4
5
class ArrayUtils
6
{
7
    /**
8
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
9
     * e restituisce l'indice.
10
     *
11
     * @param $elem mixed Elemento da cercare nell'array
12
     * @param $array Array nel quale cercare
13
     * @param $key string Nome della chiave nella quale cercare $elem
14
     *
15
     * @return mixed False se non trovato l'elemento, altrimenti l'indice in cui si è trovato il valore
16
     */
17 1
    public static function inMultiarray($elem, $array, $key)
18
    {
19 1
        foreach ($array as $indice => $value) {
20 1
            if (!is_array($value)) {
21
                return false;
22
            }
23 1
            if (array_key_exists($key, $value)) {
24 1
                foreach ($value as $nomecolonna => $colonna) {
25 1
                    if ($colonna === $elem && $nomecolonna == $key) {
26 1
                        return $indice;
27
                    }
28
                }
29
            } else {
30 1
                return false;
31
            }
32
        }
33 1
        return false;
34
    }
35
    /**
36
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
37
     * e restituisce l'indice
38
     *
39
     * @param $elem mixed Elemento da cercare nell'array
40
     * @param $array Array nel quale cercare
41
     * @param $key mixed Nome della chiave nella quale cercare $elem
42
     * @return Mixed False se non trovato l'elemento, altrimenti il vettore con tutti gli indici
43
     */
44 2
    public static function inMultiarrayTutti($elem, $array, $key)
45
    {
46
47 2
        $trovato = array();
48
49 2
        foreach ($array as $indice => $value) {
50 2
            if (!is_array($value)) {
51
                return false;
52
            }
53 2
            if (array_key_exists($key, $value)) {
54 2
                foreach ($value as $nomecolonna => $colonna) {
55 2
                    if ($colonna === $elem && $nomecolonna == $key) {
56 2
                        $trovato[] = $indice;
57
                    }
58
                }
59
            } else {
60 2
                return false;
61
            }
62
        }
63 2
        return (count($trovato) > 0 ? $trovato : false);
64
    }
65
    /**
66
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
67
     * e restituisce l'indice
68
     *
69
     * @param $array Array nel quale cercare
70
     * @param $search array Chiave-valore da cercare
71
     * @return Mixed False se non trovato l'elemento, altrimenti l'indice in cui si trova il valore
72
     */
73 1
    public static function multiInMultiarray($array, $search, $debug = false, $tutti = false)
74
    {
75 1
        $primo = true;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
76 1
        $vettorerisultati = array();
77
78 1
        foreach ($search as $key => $singolaricerca) {
79 1
            $trovato = self::inMultiarrayTutti($singolaricerca, $array, $key, $debug);
0 ignored issues
show
Unused Code introduced by
The call to Cdf\BiCoreBundle\Utils\A...ls::inMultiarrayTutti() has too many arguments starting with $debug. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

79
            /** @scrutinizer ignore-call */ 
80
            $trovato = self::inMultiarrayTutti($singolaricerca, $array, $key, $debug);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
80
81 1
            if ($trovato === false) {
82 1
                $vettorerisultati = false;
83 1
                break;
84
            }
85
86 1
            if ($primo) {
87 1
                $vettorerisultati = $trovato;
88
            } else {
89
                $vettorerisultati = array_intersect($vettorerisultati, $trovato);
90
            }
91
92 1
            $primo = false;
93
        }
94
95 1
        if ($vettorerisultati === false) {
96 1
            $risposta = false;
97 1
        } elseif ($tutti === false) {
98 1
            $risposta = reset($vettorerisultati);
99
        } else {
100 1
            $risposta = $vettorerisultati;
101
        }
102
103 1
        return $risposta;
104
    }
105
    /**
106
     * La funzione ordina un array multidimensionale $array.
107
     *
108
     * @param $array Array da ordinare
109
     * @param $key string Nome della chiave dell'array per cui ordinare
110
     * @param $type int Tipo di ordinamento SORT_ASC, SORT_DESC
111
     *
112
     * @return array Ritorna l'array ordinato
113
     *
114
     * @example arrayOrderby($rubrica,"cognome",SORT_ASC);
115
     *          <br/>$rubrica = array();<br/>
116
     *          $rubrica[] = array("matricola" => 99999, "cognome" => "rossi", "nome" => "mario");<br/>
117
     *          $rubrica[] = array("matricola" => 99998, "cognome" => "bianchi", "nome" => "andrea");
118
     *          $rubrica[] = array("matricola" => 99997, "cognome" => "verdi", "nome" => "michele");
119
     *          rusulterà<br/>$rubrica[0]("matricola"=>99998,"cognome"=>"bianchi","nome"=>"andrea")
120
     *          $rubrica[1]("matricola"=>99999,"cognome"=>"rossi","nome"=>"mario")
121
     *          $rubrica[2]("matricola"=>99997,"cognome"=>"verdi","nome"=>"michele")
122
     */
123 1
    public static function arrayOrderby()
124
    {
125 1
        $args = func_get_args();
126 1
        $data = array_shift($args);
127 1
        foreach ($args as $n => $field) {
128 1
            if (is_string($field)) {
129 1
                $tmp = array();
130 1
                foreach ($data as $key => $row) {
131 1
                    $tmp[$key] = $row[$field];
132
                }
133 1
                $args[$n] = $tmp;
134
            }
135
        }
136 1
        $args[] = &$data;
137 1
        call_user_func_array('array_multisort', $args);
138 1
        return array_pop($args);
139
    }
140
    public function arraySearchRecursive($needle, $haystack)
141
    {
142
        foreach ($haystack as $key => $val) {
143
            if (stripos(implode('', $val), $needle) > 0) {
144
                return $key;
145
            }
146
        }
147
148
        return false;
149
    }
150
    /**
151
     * La funzione ordina un array multidimensionale  che ha per indice chiavi associative.
152
     *
153
     * @param $array Array da ordinare
154
     * @param $subkey string Nome della chiave dell'array associato alla chiave per cui ordinare
155
     * @param $sort_ascending boolean Tipo di ordinamento true ASC, false DESC
156
     *
157
     * @return array Ritorna l'array ordinato
158
     *
159
     * @example sortMultiAssociativeArray($rubrica, "ordine", true);<code>
160
     *          array["nominativo" => ["nomecampo" => "nominativo","ordine" => 30],<br/><br/>
161
     *          "datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
162
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20]<br/><br/>
163
     *          ritorna:<br/><br/>
164
     *          array["datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
165
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20],<br/><br/>
166
     *          "nominativo" => ["nomecampo" => "nominativo","ordine" => 30]</code>
167
     *
168
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
169
     */
170 13
    public static function sortMultiAssociativeArray(&$array, $subkey, $sort_ascending = true)
171
    {
172
        //Se sono tutti uguali (stesso "peso") evita di fare l'ordinamento
173 13
        if (!self::isSortArray($array, $subkey)) {
174 13
            if (count($array)) {
175 13
                $temp_array[key($array)] = array_shift($array);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$temp_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $temp_array = array(); before regardless.
Loading history...
176
            }
177
178 13
            foreach ($array as $key => $val) {
179 13
                $offset = 0;
180 13
                $found = false;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
181 13
                foreach ($temp_array as $tmp_key => $tmp_val) {
182 13
                    if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
183 13
                        $temp_array = array_merge(
184 13
                            (array) array_slice($temp_array, 0, $offset),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $temp_array does not seem to be defined for all execution paths leading up to this point.
Loading history...
185 13
                            array($key => $val),
186 13
                            array_slice($temp_array, $offset)
187
                        );
188 13
                        $found = true;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
189
                    }
190 13
                    $offset++;
191
                }
192 13
                if (!$found) {
193 13
                    $temp_array = array_merge($temp_array, array($key => $val));
194
                }
195
            }
196 13
            $array = self::executeSortMultiAssociativeArray($temp_array, $sort_ascending);
197
        }
198 13
    }
199 13
    private static function isSortArray($array, $subkey)
200
    {
201 13
        $check = null;
202 13
        $diff = false;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
203 13
        $key = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $key is dead and can be removed.
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
204
        //Controlla se sono tutti uguali i valori per i quali deve fare l'ordinamento
205 13
        foreach ($array as $key => $val) {
206 13
            if (isset($check) && $check != $val[$subkey]) {
207 13
                $diff = true;
208 13
                break;
209
            } else {
210 13
                $check = $val[$subkey];
211
            }
212
        }
213 13
        return !$diff;
214
    }
215 13
    private static function executeSortMultiAssociativeArray($temp_array, $sort_ascending)
216
    {
217 13
        if ($sort_ascending) {
218 13
            $array = array_reverse($temp_array);
219
        } else {
220 1
            $array = $temp_array;
221
        }
222 13
        return $array;
223
    }
224
}
225