Completed
Pull Request — master (#69)
by Greg
01:45
created

UnstructuredDataTransformation   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 47
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A simplifyToString() 0 4 1
A transformRow() 0 8 2
A simplifyRow() 0 11 3
A isSimpleArray() 0 9 3
1
<?php
2
namespace Consolidation\OutputFormatters\Transformations;
3
4
use Consolidation\OutputFormatters\Options\FormatterOptions;
5
6
class UnstructuredDataTransformation extends \ArrayObject implements StringTransformationInterface
7
{
8
    protected $originalData;
9
10
    public function __construct($data, $fields)
11
    {
12
        $this->originalData = $data;
13
        $rows = static::transformRow($data, $fields);
14
        parent::__construct($rows);
15
    }
16
17
    public function simplifyToString(FormatterOptions $options)
18
    {
19
        return static::simplifyRow($this->getArrayCopy());
20
    }
21
22
    public static function transformRow($row, $fields)
23
    {
24
        if (empty($fields)) {
25
            return $row;
26
        }
27
        $fieldAccessor = new UnstructuredDataFieldAccessor($row);
28
        return $fieldAccessor->get($fields);
29
    }
30
31
    public static function simplifyRow($row)
32
    {
33
        if (is_string($row)) {
34
            return $row;
35
        }
36
        if (static::isSimpleArray($row)) {
37
            return implode("\n", $row);
38
        }
39
        // No good way to simplify - just dump a json fragment
40
        return json_encode($row);
41
    }
42
43
    protected static function isSimpleArray($row)
44
    {
45
        foreach ($row as $item) {
46
            if (!is_string($item)) {
47
                return false;
48
            }
49
        }
50
        return true;
51
    }
52
}
53