Completed
Branch 4.1 (fb2034)
by Andrea
04:53
created

ArrayUtils   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Test Coverage

Coverage 90.36%

Importance

Changes 0
Metric Value
wmc 40
eloc 84
dl 0
loc 211
ccs 75
cts 83
cp 0.9036
rs 9.2
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A arraySearchRecursive() 0 9 3
C sortMultiAssociativeArray() 0 41 12
A arrayOrderby() 0 16 4
B inMultiarray() 0 17 7
A multiInMultiarray() 0 31 6
B inMultiarrayTutti() 0 20 8

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
namespace Fi\CoreBundle\Utils\Arrays;
3
4
class ArrayUtils
5
{
6
    /**
7
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
8
     * e restituisce l'indice.
9
     *
10
     * @param $elem mixed Elemento da cercare nell'array
11
     * @param $array Array nel quale cercare
12
     * @param $key string Nome della chiave nella quale cercare $elem
13
     *
14
     * @return mixed False se non trovato l'elemento, altrimenti l'indice in cui si è trovato il valore
15
     */
16 1
    public static function inMultiarray($elem, $array, $key)
17
    {
18 1
        foreach ($array as $indice => $value) {
19 1
            if (!is_array($value)) {
20
                return false;
21
            }
22 1
            if (array_key_exists($key, $value)) {
23 1
                foreach ($value as $nomecolonna => $colonna) {
24 1
                    if ($colonna === $elem && $nomecolonna == $key) {
25 1
                        return $indice;
26
                    }
27
                }
28
            } else {
29 1
                return false;
30
            }
31
        }
32 1
        return false;
33
    }
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
    /**
67
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
68
     * e restituisce l'indice
69
     *
70
     * @param $array Array nel quale cercare
71
     * @param $search array Chiave-valore da cercare
72
     * @return Mixed False se non trovato l'elemento, altrimenti l'indice in cui si trova il valore
73
     */
74 1
    public static function multiInMultiarray($array, $search, $debug = false, $tutti = false)
75
    {
76 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...
77 1
        $vettorerisultati = array();
78
79 1
        foreach ($search as $key => $singolaricerca) {
80 1
            $trovato = self::inMultiarrayTutti($singolaricerca, $array, $key, $debug);
0 ignored issues
show
Unused Code introduced by
The call to Fi\CoreBundle\Utils\Arra...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

80
            /** @scrutinizer ignore-call */ 
81
            $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...
81
82 1
            if ($trovato === false) {
83 1
                $vettorerisultati = false;
84 1
                break;
85
            }
86
87 1
            if ($primo) {
88 1
                $vettorerisultati = $trovato;
89
            } else {
90
                $vettorerisultati = array_intersect($vettorerisultati, $trovato);
91
            }
92
93 1
            $primo = false;
94
        }
95
96 1
        if ($vettorerisultati === false) {
97 1
            $risposta = false;
98 1
        } elseif ($tutti === false) {
99 1
            $risposta = reset($vettorerisultati);
100
        } else {
101 1
            $risposta = $vettorerisultati;
102
        }
103
104 1
        return $risposta;
105
    }
106
107
    /**
108
     * La funzione ordina un array multidimensionale $array.
109
     *
110
     * @param $array Array da ordinare
111
     * @param $key string Nome della chiave dell'array per cui ordinare
112
     * @param $type int Tipo di ordinamento SORT_ASC, SORT_DESC
113
     *
114
     * @return array Ritorna l'array ordinato
115
     *
116
     * @example arrayOrderby($rubrica,"cognome",SORT_ASC);
117
     *          <br/>$rubrica = array();<br/>
118
     *          $rubrica[] = array("matricola" => 99999, "cognome" => "rossi", "nome" => "mario");<br/>
119
     *          $rubrica[] = array("matricola" => 99998, "cognome" => "bianchi", "nome" => "andrea");
120
     *          $rubrica[] = array("matricola" => 99997, "cognome" => "verdi", "nome" => "michele");
121
     *          rusulterà<br/>$rubrica[0]("matricola"=>99998,"cognome"=>"bianchi","nome"=>"andrea")
122
     *          $rubrica[1]("matricola"=>99999,"cognome"=>"rossi","nome"=>"mario")
123
     *          $rubrica[2]("matricola"=>99997,"cognome"=>"verdi","nome"=>"michele")
124
     */
125 1
    public static function arrayOrderby()
126
    {
127 1
        $args = func_get_args();
128 1
        $data = array_shift($args);
129 1
        foreach ($args as $n => $field) {
130 1
            if (is_string($field)) {
131 1
                $tmp = array();
132 1
                foreach ($data as $key => $row) {
133 1
                    $tmp[$key] = $row[$field];
134
                }
135 1
                $args[$n] = $tmp;
136
            }
137
        }
138 1
        $args[] = &$data;
139 1
        call_user_func_array('array_multisort', $args);
140 1
        return array_pop($args);
141
    }
142
143
    public function arraySearchRecursive($needle, $haystack)
144
    {
145
        foreach ($haystack as $key => $val) {
146
            if (stripos(implode('', $val), $needle) > 0) {
147
                return $key;
148
            }
149
        }
150
151
        return false;
152
    }
153
154
    /**
155
     * La funzione ordina un array multidimensionale  che ha per indice chiavi associative.
156
     *
157
     * @param $array Array da ordinare
158
     * @param $subkey string Nome della chiave dell'array associato alla chiave per cui ordinare
159
     * @param $sort_ascending boolean Tipo di ordinamento true ASC, false DESC
160
     *
161
     * @return array Ritorna l'array ordinato
162
     *
163
     * @example sortMultiAssociativeArray($rubrica, "ordine", true);<code>
164
     *          array["nominativo" => ["nomecampo" => "nominativo","ordine" => 30],<br/><br/>
165
     *          "datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
166
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20]<br/><br/>
167
     *          ritorna:<br/><br/>
168
     *          array["datanascita" => ["nomecampo" => "datanascita","ordine" => 10],<br/><br/>
169
     *          "telefono" => ["nomecampo" => "telefono","ordine" => 20],<br/><br/>
170
     *          "nominativo" => ["nomecampo" => "nominativo","ordine" => 30]</code>
171
     *
172
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
173
     */
174 3
    public static function sortMultiAssociativeArray(&$array, $subkey, $sort_ascending = true)
175
    {
176 3
        $check = null;
177 3
        $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...
178
        //Controlla se sono tutti uguali i valori per i quali deve fare l'ordinamento
179 3
        foreach ($array as $key => $val) {
180 3
            if (isset($check) && $check != $val[$subkey]) {
181 3
                $diff = true;
182 3
                break;
183
            } else {
184 3
                $check = $val[$subkey];
185
            }
186
        }
187
        //Se sono tutti uguali (stesso "peso") evita di fare l'ordinamento
188 3
        if ($diff) {
189 3
            if (count($array)) {
190 3
                $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...
191
            }
192
193 3
            foreach ($array as $key => $val) {
194 3
                $offset = 0;
195 3
                $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...
196 3
                foreach ($temp_array as $tmp_key => $tmp_val) {
197 3
                    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...
198 3
                        $temp_array = array_merge(
199 3
                            (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...
200 3
                            array($key => $val),
201 3
                            array_slice($temp_array, $offset)
202
                        );
203 3
                        $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...
204
                    }
205 3
                    $offset++;
206
                }
207 3
                if (!$found) {
208 3
                    $temp_array = array_merge($temp_array, array($key => $val));
209
                }
210
            }
211 3
            if ($sort_ascending) {
212 3
                $array = array_reverse($temp_array);
213
            } else {
214 1
                $array = $temp_array;
215
            }
216
        }
217 3
    }
218
}
219