Completed
Push — master ( 74371a...6da8c0 )
by Vladimir
02:21
created

GroupByFilter::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Templating\Twig\Extension;
9
10
class GroupByFilter extends AbstractTwigExtension implements TwigFilterInterface
11
{
12 5
    public function __invoke($array, $sortKey)
13
    {
14 5
        $arr = array();
15
16 5
        foreach ($array as $key => $item)
17
        {
18 5
            if (!isset($item[$sortKey]))
19
            {
20 2
                continue;
21
            }
22
23 4
            $groupBy = $item[$sortKey];
24
25 4
            if (is_bool($groupBy))
26
            {
27 1
                $groupBy = ($groupBy) ? 'true' : 'false';
28
            }
29 3
            elseif (!is_scalar($groupBy))
30
            {
31 1
                trigger_error('You cannot group by a non-scalar value', E_USER_WARNING);
32
                continue;
33
            }
34
35 3
            $arr[$groupBy][$key] = $item;
36
        }
37
38 4
        return $arr;
39
    }
40
41
    public static function get()
42
    {
43
        return new \Twig_SimpleFilter('group', new self());
44
    }
45
}
46