|
1
|
|
|
<?php |
|
2
|
|
|
namespace Consolidation\OutputFormatters\Transformations; |
|
3
|
|
|
|
|
4
|
|
|
use Dflydev\DotAccessData\Data; |
|
5
|
|
|
use Consolidation\OutputFormatters\Options\FormatterOptions; |
|
6
|
|
|
|
|
7
|
|
|
class UnstructuredDataTransformation extends \ArrayObject implements SimplifyToStringInterface |
|
8
|
|
|
{ |
|
9
|
|
|
protected $originalData; |
|
10
|
|
|
|
|
11
|
|
|
public function __construct($data, $fields) |
|
12
|
|
|
{ |
|
13
|
|
|
$this->originalData = $data; |
|
14
|
|
|
$rows = static::transformRows($data, $fields); |
|
15
|
|
|
parent::__construct($rows); |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
protected static function transformRows($data, $fields) |
|
19
|
|
|
{ |
|
20
|
|
|
$rows = []; |
|
21
|
|
|
foreach ($data as $rowid => $row) { |
|
22
|
|
|
$rows[$rowid] = static::transformRow($row, $fields); |
|
23
|
|
|
} |
|
24
|
|
|
return $rows; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
protected static function transformRow($row, $fields) |
|
28
|
|
|
{ |
|
29
|
|
|
if (empty($fields)) { |
|
30
|
|
|
return $row; |
|
31
|
|
|
} |
|
32
|
|
|
$data = new Data($row); |
|
33
|
|
|
$result = new Data(); |
|
34
|
|
|
foreach ($fields as $key => $label) { |
|
35
|
|
|
$item = $data->get($key); |
|
36
|
|
|
if (isset($item)) { |
|
37
|
|
|
if ($label == '.') { |
|
38
|
|
|
if (!is_array($item)) { |
|
39
|
|
|
return $item; |
|
40
|
|
|
} |
|
41
|
|
|
foreach ($item as $key => $value) { |
|
42
|
|
|
$result->set($key, $value); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
else { |
|
46
|
|
|
$result->set($label, $data->get($key)); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
return $result->export(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function simplifyToString(FormatterOptions $options) |
|
54
|
|
|
{ |
|
55
|
|
|
$result = ''; |
|
56
|
|
|
$iterator = $this->getIterator(); |
|
57
|
|
|
while($iterator->valid()) { |
|
58
|
|
|
$simplifiedRow = $this->simplifyRow($iterator->current()); |
|
59
|
|
|
if (isset($simplifiedRow)) { |
|
60
|
|
|
$result .= "$simplifiedRow\n"; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$iterator->next(); |
|
64
|
|
|
} |
|
65
|
|
|
return $result; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
protected function simplifyRow($row) |
|
69
|
|
|
{ |
|
70
|
|
|
if (is_string($row)) { |
|
71
|
|
|
return $row; |
|
72
|
|
|
} |
|
73
|
|
|
if ($this->isSimpleArray($row)) { |
|
74
|
|
|
return implode("\n", $row); |
|
75
|
|
|
} |
|
76
|
|
|
// No good way to simplify - just dump a json fragment |
|
77
|
|
|
return json_encode($row); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
protected function isSimpleArray($row) |
|
81
|
|
|
{ |
|
82
|
|
|
foreach ($row as $item) { |
|
83
|
|
|
if (!is_string($item)) { |
|
84
|
|
|
return false; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
return true; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|