Completed
Push — master ( b139e2...07b7da )
by Daniel
03:29
created

src/Traverse.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
namespace Narrowspark\Arr;
3
4
class Traverse
5
{
6
    /**
7
     * Applies the callback to the elements of the given arrays
8
     *
9
     * @param array    $array
10
     * @param callable $callback
11
     *
12
     * @return array
13
     */
14
    public function map(array $array, callable $callback)
15
    {
16
        $newArray = [];
17
18
        foreach ($array as $key => $item) {
19
            $result = call_user_func($callback, $item, $key);
20
21
            $newArray = is_array($result) ?
22
                array_replace_recursive($array, $result) :
23
                array_merge_recursive($array, (array) $result);
24
        }
25
26
        return $newArray;
27
    }
28
29
    /**
30
     * Filters each of the given values through a function.
31
     *
32
     * @param array    $array
33
     * @param callable $callback
34
     *
35
     * @return array
36
     */
37
    public function filter(array $array, callable $callback)
38
    {
39
        $newArray = [];
40
41
        foreach ($array as $key => $item) {
42
            if (call_user_func($callback, $item, $key)) {
43
                $newArray[$key] = $item;
44
            }
45
        }
46
47
        return $newArray;
48
    }
49
50
    /**
51
     *  The opposite of filter().
52
     *
53
     *  @param array    $array
54
     *  @param callable $cb Function to filter values.
55
     *
56
     *  @return array filtered array.
57
     */
58
    public function reject(array $array, callable $cb)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $cb. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
59
    {
60
        return $this->filter($array, function ($value, $key) use ($cb) {
61
            return !call_user_func($cb, $value, $key);
62
        });
63
    }
64
}
65