TableFormatter   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 96.88%

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 8
dl 0
loc 128
ccs 31
cts 32
cp 0.9688
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validDataTypes() 0 8 1
A validate() 0 14 2
B write() 0 39 6
A wrap() 0 12 2
A addCustomTableStyles() 0 21 2
1
<?php
2
namespace Consolidation\OutputFormatters\Formatters;
3
4
use Symfony\Component\Console\Output\OutputInterface;
5
use Symfony\Component\Console\Helper\Table;
6
use Symfony\Component\Console\Helper\TableStyle;
7
8
use Consolidation\OutputFormatters\Validate\ValidDataTypesInterface;
9
use Consolidation\OutputFormatters\Options\FormatterOptions;
10
use Consolidation\OutputFormatters\Validate\ValidDataTypesTrait;
11
use Consolidation\OutputFormatters\StructuredData\TableDataInterface;
12
use Consolidation\OutputFormatters\Transformations\ReorderFields;
13
use Consolidation\OutputFormatters\Exception\IncompatibleDataException;
14
use Consolidation\OutputFormatters\Transformations\WordWrapper;
15
use Consolidation\OutputFormatters\Formatters\HumanReadableFormat;
16
17
/**
18
 * Display a table of data with the Symfony Table class.
19
 *
20
 * This formatter takes data of either the RowsOfFields or
21
 * PropertyList data type.  Tables can be rendered with the
22
 * rows running either vertically (the normal orientation) or
23
 * horizontally.  By default, associative lists will be displayed
24
 * as two columns, with the key in the first column and the
25
 * value in the second column.
26
 */
27
class TableFormatter implements FormatterInterface, ValidDataTypesInterface, RenderDataInterface, MetadataFormatterInterface, HumanReadableFormat
28
{
29
    use ValidDataTypesTrait;
30
    use RenderTableDataTrait;
31
    use MetadataFormatterTrait;
32 9
33
    protected $fieldLabels;
34 9
    protected $defaultFields;
35 9
36
    public function __construct()
37
    {
38
    }
39
40 9
    public function validDataTypes()
41
    {
42 9
        return
43 2
            [
44 2
                new \ReflectionClass('\Consolidation\OutputFormatters\StructuredData\RowsOfFields'),
45 9
                new \ReflectionClass('\Consolidation\OutputFormatters\StructuredData\PropertyList')
46
            ];
47
    }
48
49
    /**
50 9
     * @inheritdoc
51
     */
52
    public function validate($structuredData)
53
    {
54
        // If the provided data was of class RowsOfFields
55 9
        // or PropertyList, it will be converted into
56 2
        // a TableTransformation object by the restructure call.
57 2
        if (!$structuredData instanceof TableDataInterface) {
58 2
            throw new IncompatibleDataException(
59
                $this,
60 2
                $structuredData,
61 2
                $this->validDataTypes()
62
            );
63 2
        }
64
        return $structuredData;
65 7
    }
66
67
    /**
68
     * @inheritdoc
69
     */
70
    public function write(OutputInterface $output, $tableTransformer, FormatterOptions $options)
71
    {
72 7
        $headers = [];
0 ignored issues
show
Unused Code introduced by
$headers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
73
        $defaults = [
74
            FormatterOptions::TABLE_STYLE => 'consolidation',
75 7
            FormatterOptions::INCLUDE_FIELD_LABELS => true,
76 7
        ];
77
78
        $table = new Table($output);
79 7
80 7
        static::addCustomTableStyles($table);
81 7
82 7
        $table->setStyle($options->get(FormatterOptions::TABLE_STYLE, $defaults));
83 7
        $isList = $tableTransformer->isList();
84 7
        $includeHeaders = $options->get(FormatterOptions::INCLUDE_FIELD_LABELS, $defaults);
85 4
        $listDelimiter = $options->get(FormatterOptions::LIST_DELIMITER, $defaults);
86 4
87 7
        $headers = $tableTransformer->getHeaders();
88 7
        $data = $tableTransformer->getTableData($includeHeaders && $isList);
89 7
90
        if ($listDelimiter) {
91
            if (!empty($headers)) {
92
                array_splice($headers, 1, 0, ':');
93
            }
94
            $data = array_map(function ($item) {
95
                array_splice($item, 1, 0, ':');
96
                return $item;
97
            }, $data);
98
        }
99
100
        if ($includeHeaders && !$isList) {
101
            $table->setHeaders($headers);
102
        }
103
104
        // todo: $output->getFormatter();
105
        $data = $this->wrap($headers, $data, $table->getStyle(), $options);
106
        $table->setRows($data);
107
        $table->render();
108
    }
109
110
    /**
111
     * Wrap the table data
112
     * @param array $data
113
     * @param TableStyle $tableStyle
114
     * @param FormatterOptions $options
115
     * @return array
116
     */
117
    protected function wrap($headers, $data, TableStyle $tableStyle, FormatterOptions $options)
118
    {
119
        $wrapper = new WordWrapper($options->get(FormatterOptions::TERMINAL_WIDTH));
120
        $wrapper->setPaddingFromStyle($tableStyle);
121
        if (!empty($headers)) {
122
            $headerLengths = array_map(function ($item) {
123
                return strlen($item);
124
            }, $headers);
125
            $wrapper->setMinimumWidths($headerLengths);
126
        }
127
        return $wrapper->wrap($data);
128
    }
129
130
    /**
131
     * Add our custom table style(s) to the table.
132
     */
133
    protected static function addCustomTableStyles($table)
134
    {
135
        // The 'consolidation' style is the same as the 'symfony-style-guide'
136
        // style, except it maintains the colored headers used in 'default'.
137
        $consolidationStyle = new TableStyle();
138
139
        if (method_exists($consolidationStyle, 'setHorizontalBorderChars')) {
140
            $consolidationStyle
141
                ->setHorizontalBorderChars('-')
142
                ->setVerticalBorderChars(' ')
143
                ->setDefaultCrossingChar(' ')
144
            ;
145
        } else {
146
            $consolidationStyle
0 ignored issues
show
Bug introduced by
The method setHorizontalBorderChar() does not exist on Symfony\Component\Console\Helper\TableStyle. Did you maybe mean setHorizontalBorderChars()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
147
                ->setHorizontalBorderChar('-')
148
                ->setVerticalBorderChar(' ')
149
                ->setCrossingChar(' ')
150
            ;
151
        }
152
        $table->setStyleDefinition('consolidation', $consolidationStyle);
153
    }
154
}
155