summaryrefslogtreecommitdiffstats
path: root/library/Director/PropertyModifier/PropertyModifierSimpleGroupBy.php
blob: 6c1452f60080d3ca646971eb79231c563a68b71f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

namespace Icinga\Module\Director\PropertyModifier;

use Icinga\Module\Director\Hook\PropertyModifierHook;
use Icinga\Module\Director\Web\Form\QuickForm;

class PropertyModifierSimpleGroupBy extends PropertyModifierHook
{
    private $keptRows = [];

    public function getName()
    {
        return mt('director', 'Group by a column, aggregate others');
    }

    public function requiresRow()
    {
        return true;
    }

    public function transform($value)
    {
        $row = $this->getRow();
        $aggregationColumns = preg_split(
            '/\s*,\s*/',
            $this->getSetting('aggregation_columns'),
            -1,
            PREG_SPLIT_NO_EMPTY
        );
        if (isset($this->keptRows[$value])) {
            foreach ($aggregationColumns as $column) {
                if (isset($row->$column)) {
                    $this->keptRows[$value]->{$column} = array_unique(array_merge(
                        $this->keptRows[$value]->{$column},
                        [$row->$column]
                    ));
                    sort($this->keptRows[$value]->{$column});
                }
            }
            $this->rejectRow();
        } else {
            foreach ($aggregationColumns as $column) {
                if (isset($row->$column)) {
                    $row->$column = [$row->$column];
                } else {
                    $row->$column = [];
                }
            }

            $this->keptRows[$value] = $row;
        }

        return $value;
    }

    public static function addSettingsFormFields(QuickForm $form)
    {
        $form->addElement('text', 'aggregation_columns', [
            'label'       => $form->translate('Aggregation Columns'),
            'description' => $form->translate(
                'Comma-separated list of columns that should be aggregated (transformed into an Array).'
                . ' For all other columns only the first value will be kept.'
            ),
            'required'    => true,
        ]);
    }
}