Completed
Push — master ( 077837...1dc5b3 )
by Andrea
51:40 queued 46:37
created

ArrayUtils::arrayOrderby()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 4
nop 0
dl 0
loc 17
ccs 12
cts 12
cp 1
crap 4
rs 9.9
c 0
b 0
f 0
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
                return false;
31
            }
32
        }
33
34 1
        return false;
35
    }
36
37
    /**
38
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
39
     * e restituisce l'indice.
40
     *
41
     * @param $elem mixed Elemento da cercare nell'array
42
     * @param $array Array nel quale cercare
43
     * @param $key mixed Nome della chiave nella quale cercare $elem
44
     *
45
     * @return mixed False se non trovato l'elemento, altrimenti il vettore con tutti gli indici
46
     */
47 2
    public static function inMultiarrayTutti($elem, $array, $key)
48
    {
49 2
        $trovato = array();
50
51 2
        foreach ($array as $indice => $value) {
52 2
            if (!is_array($value)) {
53
                return false;
54
            }
55 2
            if (array_key_exists($key, $value)) {
56 2
                foreach ($value as $nomecolonna => $colonna) {
57 2
                    if ($colonna === $elem && $nomecolonna == $key) {
58 2
                        $trovato[] = $indice;
59
                    }
60
                }
61
            } else {
62
                return false;
63
            }
64
        }
65
66 2
        return count($trovato) > 0 ? $trovato : false;
67
    }
68
69
    /**
70
     * La funzione cerca un valore $elem nell'array multidimensionale $array all'interno di ogni elemento con chiave $key di ogni riga di array
71
     * e restituisce l'indice.
72
     *
73
     * @param $array Array nel quale cercare
74
     * @param $search array Chiave-valore da cercare
75
     *
76
     * @return mixed False se non trovato l'elemento, altrimenti l'indice in cui si trova il valore
77
     */
78 1
    public static function multiInMultiarray($array, $search, $debug = false, $tutti = false)
79
    {
80 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...
81 1
        $vettorerisultati = array();
82
83 1
        foreach ($search as $key => $singolaricerca) {
84 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

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