-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlatten.php
More file actions
118 lines (97 loc) · 2.66 KB
/
Flatten.php
File metadata and controls
118 lines (97 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
class Flatten {
/**
* @var string
* Source Filename
*/
protected $source;
/**
* @var string
* Destination Filename
*/
protected $destination;
/**
* @param string $source
* @param string $destination
*/
public function __construct($source = 'test.json', $destination = 'flat.json')
{
$this->source = $source;
$this->destination = $destination;
}
/**
* @param array $input
* Takes an optional array and returns the flattened array
* If left blank we will read from / write to files instead
* @return array / bool
*/
public function run(array $input = null)
{
$data = $input ?: $this->readJsonFile($this->source);
$flat = $this->flatten($data);
if ( ! is_null($input) ) {
return $flat;
}
return $this->writeJsonFile($this->destination, $flat);
}
public function loadConfig($filename)
{
$this->checkFileExists($filename);
$config = include($filename);
if ( ! array_key_exists('source', $config) || ! array_key_exists('destination', $config) ) {
throw new UnexpectedValueException("Please ensure '$filename' specifies a source and a destination");
}
$this->source = $config['source'];
$this->destination = $config['destination'];
}
protected function checkFileExists($filename)
{
if ( ! file_exists($filename) ) {
throw new FileDoesNotExistException("$filename does not exist.");
}
}
/**
* @param $filename
* @return array
*/
protected function readJsonFile($filename)
{
$this->checkFileExists($filename);
$data = file_get_contents($filename);
return json_decode($data);
}
/**
* @param $filename
* @param $data
* @return bool (Success)
*/
protected function writeJsonFile($filename, $data)
{
$json = json_encode($data, true);
return file_put_contents($filename, $json) !== false;
}
/**
* @param array $input
* @return array
*
* Returns the flattened input array
*/
protected function flatten(array $input)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($input));
$output = [];
foreach($iterator as $value) {
$output[] = $value;
}
return $output;
}
/**
* @param $data
*
* Used for testing / development purposes in lieu of Laravel's dd()
*/
protected function displayJson($data)
{
echo json_encode($data, true) . PHP_EOL;
}
}