Failed Conditions
Pull Request — master (#326)
by
unknown
02:33
created

functions.php ➔ get_depth()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
########################################################################
4
// Human Time Ago
5
// @param $timestamp	=> timestamp (mandatory)
6
// @param $locales	=> locales (mandatory)
7
//
8
// Return time ago at human format (eg: 2 hours ago)
9
########################################################################
10
11
function time_ago($timestamp, $locales)
12
{
13
14
	// Set up our variables.
15
	$minute_in_seconds = 60;
16
	$hour_in_seconds   = $minute_in_seconds * 60;
17
	$day_in_seconds	   = $hour_in_seconds * 24;
18
	$week_in_seconds   = $day_in_seconds * 7;
19
	$month_in_seconds  = $day_in_seconds * 30;
20
	$year_in_seconds   = $day_in_seconds * 365;
21
22
	// current time
23
	$now = time();
24
25
	// Calculate the time difference between the current time reference point and the timestamp we're comparing.
26
	// The difference is defined negative, when in the future.
27
	$time_difference = $now - $timestamp;
28
29
	// Calculate the time ago using the smallest applicable unit.
30
	if ($time_difference < $hour_in_seconds) {
31
		$difference_value = abs(round($time_difference / $minute_in_seconds));
32
		$difference_label = 'MINUTE';
33
	} elseif ($time_difference < $day_in_seconds) {
34
		$difference_value = abs(round($time_difference / $hour_in_seconds));
35
		$difference_label = 'HOUR';
36
	} elseif ($time_difference < $week_in_seconds) {
37
		$difference_value = abs(round($time_difference / $day_in_seconds));
38
		$difference_label = 'DAY';
39
	} elseif ($time_difference < $month_in_seconds) {
40
		$difference_value = abs(round($time_difference / $week_in_seconds));
41
		$difference_label = 'WEEK';
42
	} elseif ($time_difference < $year_in_seconds) {
43
		$difference_value = abs(round($time_difference / $month_in_seconds));
44
		$difference_label = 'MONTH';
45
	} else {
46
		$difference_value = abs(round($time_difference / $year_in_seconds));
47
		$difference_label = 'YEAR';
48
	}
49
50
	// plural
51
	if ($difference_value != 1) {
52
		$difference_label = $difference_label.'S';
53
	}
54
55
	if ($time_difference <= 0) {
56
		// Present
57
		return sprintf($locales->TIME_LEFT, $difference_value.' '.$locales->$difference_label);
58
	} else {
59
		// Past
60
		return sprintf($locales->TIME_AGO, $difference_value.' '.$locales->$difference_label);
61
	}
62
}
63
64
65
########################################################################
66
// Percent calculator
67
// @param $val		=> int (mandatory)
68
// @param $val_total	=> int (mandatory)
69
//
70
// Return pourcent from total
71
########################################################################
72
73
function percent($val, $val_total)
74
{
75
	$count1 = $val_total / $val;
76
	$count2 = $count1 * 100;
77
78
	$count = number_format($count2, 0);
79
80
	return $count;
81
}
82
83
84
########################################################################
85
// File version (unix timestamp)
86
// @param $url		=> string (mandatory)
87
//
88
// Return $url with last_modified unix timestamp before suffix
89
########################################################################
90
91
function auto_ver($url)
92
{
93
	$path = pathinfo($url);
94
	$ver = '.'.filemtime(SYS_PATH.'/'.$url).'.';
95
	echo $path['dirname'].'/'.preg_replace('/\.(css|js)$/', $ver."$1", $path['basename']);
96
}
97
98
99
########################################################################
100
// File age in secs
101
// @param $filepath     => string (mandatory)
102
//
103
// Return file age of file in secs, PHP_INT_MAX if file doesn't exist
104
########################################################################
105
106
function file_update_ago($filepath)
107
{
108
	if (is_file($filepath)) {
109
		$filemtime = filemtime($filepath);
110
		$now = time();
111
		$diff = $now - $filemtime;
112
		return $diff;
113
	}
114
	// file doesn't exist yet!
115
	return PHP_INT_MAX;
116
}
117
118
119
########################################################################
120
// Only keep data after $timestamp in $array (compared to 'timestamp' key)
121
// @param $array     => array (mandatory)
122
// @param $timestamp => int (mandatory)
123
//
124
// Return trimmed array
125
########################################################################
126
127
function trim_stats_json($array, $timestamp)
128
{
129
	foreach ($array as $key => $value) {
130
		if ($value['timestamp'] < $timestamp) {
131
			unset($array[$key]);
132
		}
133
	}
134
	return $array;
135
}
136
137
138
########################################################################
139
// gym level from prestige value
140
// @param $prestige => int (mandatory)
141
//
142
// Return gym level
143
########################################################################
144
145
function gym_level($prestige)
146
{
147
	if ($prestige == 0) {
148
		$gym_level = 0;
149
	} elseif ($prestige < 2000) {
150
		$gym_level = 1;
151
	} elseif ($prestige < 4000) {
152
		$gym_level = 2;
153
	} elseif ($prestige < 8000) {
154
		$gym_level = 3;
155
	} elseif ($prestige < 12000) {
156
		$gym_level = 4;
157
	} elseif ($prestige < 16000) {
158
		$gym_level = 5;
159
	} elseif ($prestige < 20000) {
160
		$gym_level = 6;
161
	} elseif ($prestige < 30000) {
162
		$gym_level = 7;
163
	} elseif ($prestige < 40000) {
164
		$gym_level = 8;
165
	} elseif ($prestige < 50000) {
166
		$gym_level = 9;
167
	} else {
168
		$gym_level = 10;
169
	}
170
171
	return $gym_level;
172
}
173
174
function get_depth($arr) {
175
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
176
    $depth = 0;
177
    foreach ( $it as $v ) {
0 ignored issues
show
Coding Style introduced by
Space found after opening bracket of FOREACH loop
Loading history...
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
178
        $it->getDepth() > $depth and $depth = $it->getDepth();
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...
179
    }
180
    return $depth;
181
}
182
    
183
function get_tree_at_depth($trees, $depth, $max_pokemon, $currentDepth = 0) {
184
185
    if ($depth == $currentDepth) {
186
        return $trees;
187
    } else {
188
        foreach ($trees as $temp) {
189
            $tree = $temp->evolutions;
190
            $resultsTemp = get_tree_at_depth($tree, $depth, $max_pokemon, $currentDepth + 1);
191
            $results;
0 ignored issues
show
Bug introduced by
The variable $results 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...
192
            foreach ($resultsTemp as $res) {
193
                if ($res->id <= $max_pokemon) {
194
                    $results[] = $res;
195
                }
196
            }
197
            if (is_null($results)) {
198
                return null;
199
            }
200
            $count = count($results);
201
            $i = 0;
202
            foreach ($results as $res) {
203
                if ($count != 1) {
204
                    $num = $i / ($count-1);
205
                    if ($num < 0.5) {
206
                        $res->array_sufix = "_up";
207
                    } elseif ($num > 0.5) {
208
                        $res->array_sufix = "_down";
209
                    }
210
                }
211
                $arr[] = $res;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$arr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $arr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
212
                $i++;
213
            }
214
        }
215
        return $arr;
0 ignored issues
show
Bug introduced by
The variable $arr 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...
216
    }
217
218
}
219