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

GroupByFilter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 80%

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 0
cbo 2
dl 0
loc 36
ccs 12
cts 15
cp 0.8
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B __invoke() 0 28 6
A get() 0 4 1
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