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

UnstructuredDataTransformation::isSimpleArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 1
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