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
|
|
|
} else { |
45
|
|
|
$result->set($label, $data->get($key)); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
return $result->export(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function simplifyToString(FormatterOptions $options) |
53
|
|
|
{ |
54
|
|
|
$result = ''; |
55
|
|
|
$iterator = $this->getIterator(); |
56
|
|
|
while ($iterator->valid()) { |
57
|
|
|
$simplifiedRow = $this->simplifyRow($iterator->current()); |
58
|
|
|
if (isset($simplifiedRow)) { |
59
|
|
|
$result .= "$simplifiedRow\n"; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$iterator->next(); |
63
|
|
|
} |
64
|
|
|
return $result; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected function simplifyRow($row) |
68
|
|
|
{ |
69
|
|
|
if (is_string($row)) { |
70
|
|
|
return $row; |
71
|
|
|
} |
72
|
|
|
if ($this->isSimpleArray($row)) { |
73
|
|
|
return implode("\n", $row); |
74
|
|
|
} |
75
|
|
|
// No good way to simplify - just dump a json fragment |
76
|
|
|
return json_encode($row); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
protected function isSimpleArray($row) |
80
|
|
|
{ |
81
|
|
|
foreach ($row as $item) { |
82
|
|
|
if (!is_string($item)) { |
83
|
|
|
return false; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
return true; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|