Completed
Pull Request — master (#17)
by Greg
02:29
created

SectionsFormatter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 4
c 3
b 0
f 2
lcom 0
cbo 6
dl 0
loc 40
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 14 2
A write() 0 14 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\StructuredData\TableDataInterface;
11
use Consolidation\OutputFormatters\Transformations\ReorderFields;
12
use Consolidation\OutputFormatters\Exception\IncompatibleDataException;
13
use Consolidation\OutputFormatters\StructuredData\AssociativeList;
14
15
/**
16
 * Display sections of data.
17
 *
18
 * This formatter takes data in the RowsOfFields data type.
19
 * Each row represents one section; the data in each section
20
 * is rendered in two columns, with the key in the first column
21
 * and the value in the second column.
22
 */
23
class SectionsFormatter implements FormatterInterface, ValidationInterface, RenderDataInterface
24
{
25
    use RenderTableDataTrait;
26
27
    /**
28
     * @inheritdoc
29
     */
30
    public function validate($structuredData)
31
    {
32
        // If the provided data was of class RowsOfFields
33
        // or AssociativeList, it will be converted into
34
        // a TableTransformation object by the restructure call.
35
        if (!$structuredData instanceof TableDataInterface) {
36
            throw new IncompatibleDataException(
37
                $this,
38
                $structuredData,
39
                new \ReflectionClass('\Consolidation\OutputFormatters\StructuredData\RowsOfFields')
40
            );
41
        }
42
        return $structuredData;
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public function write(OutputInterface $output, $tableTransformer, $options = [])
49
    {
50
        $table = new Table($output);
51
        $table->setStyle('compact');
52
        foreach ($tableTransformer as $rowid => $row) {
53
            $rowLabel = $tableTransformer->getRowLabel($rowid);
54
            $output->writeln('');
55
            $output->writeln($rowLabel); // TODO: convert to a label
56
            $sectionData = new AssociativeList($row);
57
            $sectionTableTransformer = $sectionData->restructure([], $options);
58
            $table->setRows($sectionTableTransformer->getTableData(true));
59
            $table->render();
60
        }
61
    }
62
}
63