Completed
Pull Request — master (#16)
by Greg
02:48
created

ReorderFields::reorder()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 9.2
cc 4
eloc 8
nc 4
nop 3
crap 4
1
<?php
2
namespace Consolidation\OutputFormatters\Transformations;
3
4
/**
5
 * Reorder the field labels based on the user-selected fields
6
 * to display.
7
 */
8
class ReorderFields
9
{
10
    /**
11
     * Given a simple list of user-supplied field keys or field labels,
12
     * return a reordered version of the field labels matching the
13
     * user selection.
14
     *
15
     * @param string|array $fields The user-selected fields
16
     * @param array $fieldLabels An associative array mapping the field
17
     *   key to the field label
18
     * @param array $data The data that will be rendered.
19
     *
20
     * @return array
21
     */
22 7
    public function reorder($fields, $fieldLabels, $data)
23
    {
24 7
        if (empty($fieldLabels) && !empty($data)) {
25 5
            $firstRow = reset($data);
26 5
            $fieldLabels = array_combine(array_keys($firstRow), array_map('ucfirst', array_keys($firstRow)));
27 5
        }
28 7
        $fields = $this->getSelectedFieldKeys($fields, $fieldLabels);
29 7
        if (empty($fields)) {
30 7
            return $fieldLabels;
31
        }
32 2
        return $this->reorderFieldLabels($fields, $fieldLabels, $data);
33
    }
34
35 2
    protected function reorderFieldLabels($fields, $fieldLabels, $data)
36
    {
37 2
        $result = [];
38 2
        $firstRow = reset($data);
39 2
        foreach ($fields as $field) {
40 2
            if (array_key_exists($field, $firstRow)) {
41 2
                if (array_key_exists($field, $fieldLabels)) {
42 2
                    $result[$field] = $fieldLabels[$field];
43 2
                }
44 2
            }
45 2
        }
46 2
        return $result;
47
    }
48
49 7
    protected function getSelectedFieldKeys($fields, $fieldLabels)
50
    {
51 7
        if (is_string($fields)) {
52 1
            $fields = explode(',', $fields);
53 1
        }
54 7
        $fieldLablesReverseMap = array_combine(array_values($fieldLabels), array_keys($fieldLabels));
55 7
        $selectedFields = [];
56 7
        foreach ($fields as $field) {
57 2
            if (array_key_exists($field, $fieldLabels)) {
58 2
                $selectedFields[] = $field;
59 2
            } elseif (array_key_exists($field, $fieldLablesReverseMap)) {
60 2
                $selectedFields[] = $fieldLablesReverseMap[$field];
61 2
            }
62 7
        }
63 7
        return $selectedFields;
64
    }
65
}
66