Completed
Pull Request — master (#10)
by Greg
02:12
created

TableFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 51
wmc 7
lcom 1
cbo 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A configure() 0 6 2
A validate() 0 10 2
A write() 0 15 2
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\ConfigureInterface;
9
use Consolidation\OutputFormatters\ValidationInterface;
10
use Consolidation\OutputFormatters\Transformations\TableTransformation;
11
use Consolidation\OutputFormatters\Transformations\PropertyParser;
12
use Consolidation\OutputFormatters\Transformations\ReorderFields;
13
14
class TableFormatter implements FormatterInterface, ConfigureInterface, ValidationInterface
15
{
16
    protected $fieldLabels;
17
    protected $defaultFields;
18
    protected $tableStyle;
19
20
    public function __construct()
21
    {
22
        $this->tableStyle = 'default';
23
    }
24
25
    /**
26
     * @inheritdoc
27
     */
28
    public function configure($configurationData)
29
    {
30
        if (isset($configurationData['table-style'])) {
31
            $this->tableStyle = $configurationData['table-style'];
32
        }
33
    }
34
35
    public function validate($structuredData)
36
    {
37
        // If the returned data is of class RowsOfFields, that will
38
        // be converted into a TableTransformation object.
39
        if (!$structuredData instanceof TableTransformation) {
40
            // TODO: Define our own Exception class
41
            throw new \Exception("Data provided to table formatter must be an instance of RowsOfFields. Instead, a " . get_class($structuredData) . " was provided.", 1);
42
        }
43
        return $structuredData;
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function write(OutputInterface $output, $tableTransformer, $options = [])
50
    {
51
        $options += [
52
            'table-style' => $this->tableStyle,
53
            'include-field-labels' => true,
54
        ];
55
56
        $table = new Table($output);
57
        $table->setStyle($options['table-style']);
58
        if ($options['include-field-labels']) {
59
            $table->setHeaders($tableTransformer->getHeaders());
60
        }
61
        $table->setRows($tableTransformer->getData());
62
        $table->render();
63
    }
64
}
65