Completed
Push — master ( 0de9b9...2b8d14 )
by Alexpts
05:13
created

ArrayHelper::partition()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.7
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
namespace PTS\Tools;
4
5
class ArrayHelper
6
{
7
8 2
    public function partition(array $collection, callable ...$callbacks): array
9
    {
10 2
        $partitions = array_fill(0, count($callbacks) + 1, []);
11
12 2
        foreach ($collection as $index => $element) {
13 2
            foreach ($callbacks as $partition => $callback) {
14 2
                if ($callback($element, $index, $collection)) {
15 2
                    $partitions[$partition][] = $element;
16 2
                    continue 2;
17
                }
18
            }
19 2
            $partition++;
0 ignored issues
show
Bug introduced by
The variable $partition 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...
20 2
            $partitions[$partition][] = $element;
21
        }
22
23 2
        return $partitions;
24
    }
25
}
26