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
|
|
|
public function reorder($fields, $fieldLabels, $data) |
23
|
|
|
{ |
24
|
|
|
$fields = $this->getSelectedFieldKeys($fields, $fieldLabels); |
25
|
|
|
if (empty($fieldLabels)) { |
26
|
|
|
$fieldLabels = array_combine(array_keys($data[0]), array_keys($data[0])); |
27
|
|
|
} |
28
|
|
|
if (empty($fields)) { |
29
|
|
|
return $fieldLabels; |
30
|
|
|
} |
31
|
|
|
return $this->reorderFieldLabels($fields, $fieldLabels, $data); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
View Code Duplication |
protected function reorderFieldLabels($fields, $fieldLabels, $data) |
|
|
|
|
35
|
|
|
{ |
36
|
|
|
$result = []; |
37
|
|
|
foreach ($fields as $field) { |
38
|
|
|
if (array_key_exists($field, $data[0])) { |
39
|
|
|
if (array_key_exists($field, $fieldLabels)) { |
40
|
|
|
$result[$field] = $fieldLabels[$field]; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
return $result; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function getSelectedFieldKeys($fields, $fieldLabels) |
48
|
|
|
{ |
49
|
|
|
if (is_string($fields)) { |
50
|
|
|
$fields = explode(',', $fields); |
51
|
|
|
} |
52
|
|
|
$fieldLablesReverseMap = array_combine(array_values($fieldLabels), array_keys($fieldLabels)); |
53
|
|
|
$selectedFields = []; |
54
|
|
|
foreach ($fields as $field) { |
55
|
|
|
if (array_key_exists($field, $fieldLabels)) { |
56
|
|
|
$selectedFields[] = $field; |
57
|
|
|
} elseif (array_key_exists($field, $fieldLablesReverseMap)) { |
58
|
|
|
$selectedFields[] = $fieldLablesReverseMap[$field]; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
return $selectedFields; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.