1
|
|
|
<?php |
2
|
|
|
namespace Consolidation\OutputFormatters\Formatters; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
5
|
|
|
use Symfony\Component\Console\Helper\Table; |
6
|
|
|
|
7
|
|
|
use Consolidation\OutputFormatters\FormatterInterface; |
8
|
|
|
use Consolidation\OutputFormatters\ConfigurationAwareInterface; |
9
|
|
|
use Consolidation\OutputFormatters\Transformations\TableTransformation; |
10
|
|
|
use Consolidation\OutputFormatters\Transformations\PropertyParser; |
11
|
|
|
|
12
|
|
|
class TableFormatter implements FormatterInterface, ConfigurationAwareInterface |
13
|
|
|
{ |
14
|
|
|
protected $fieldLabels; |
15
|
|
|
protected $defaultFields; |
16
|
|
|
protected $tableStyle; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @inheritdoc |
20
|
|
|
*/ |
21
|
|
|
public function configure($configurationData) |
22
|
|
|
{ |
23
|
|
|
$configurationData += [ |
24
|
|
|
'field-labels' => [], |
25
|
|
|
'default-fields' => [], |
26
|
|
|
'table-style' => 'default', |
27
|
|
|
]; |
28
|
|
|
|
29
|
|
|
$this->fieldLabels = PropertyParser::parse($configurationData['field-labels']); |
30
|
|
|
$this->defaultFields = PropertyParser::parse($configurationData['default-fields']); |
31
|
|
|
$this->tableStyle = $configurationData['table-style']; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @inheritdoc |
36
|
|
|
*/ |
37
|
|
|
public function write($data, $options, OutputInterface $output) |
38
|
|
|
{ |
39
|
|
|
$options += [ |
40
|
|
|
'table-style' => $this->tableStyle, |
41
|
|
|
'fields' => $this->defaultFields, |
42
|
|
|
'include-field-labels' => true, |
43
|
|
|
]; |
44
|
|
|
$fieldLabels = $this->selectFieldLabels($options['fields'], $this->fieldLabels, $data); |
45
|
|
|
$tableTransformer = new TableTransformation($data, $fieldLabels, $options); |
46
|
|
|
|
47
|
|
|
$table = new Table($output); |
48
|
|
|
$table->setStyle($options['table-style']); |
49
|
|
|
if ($options['include-field-labels']) { |
50
|
|
|
$table->setHeaders($tableTransformer->getHeaders()); |
51
|
|
|
} |
52
|
|
|
$table->setRows($tableTransformer->getData()); |
53
|
|
|
$table->render(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
protected function selectFieldLabels($fields, $fieldLabels, $data) |
57
|
|
|
{ |
58
|
|
|
$result = []; |
59
|
|
|
if (empty($fieldLabels)) { |
60
|
|
|
$fieldLabels = array_combine(array_keys($data[0]), array_keys($data[0])); |
61
|
|
|
} |
62
|
|
|
if (empty($fields)) { |
63
|
|
|
return $fieldLabels; |
64
|
|
|
} |
65
|
|
|
foreach ($fields as $field) |
66
|
|
|
{ |
67
|
|
|
if (array_key_exists($field, $data[0])) { |
68
|
|
|
if (array_key_exists($field, $fieldLabels)) { |
69
|
|
|
$result[$field] = $fieldLabels[$field]; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
return $result; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|