-
Notifications
You must be signed in to change notification settings - Fork 4
/
Flatten.php
80 lines (67 loc) · 1.76 KB
/
Flatten.php
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
<?php
namespace Camillebaronnet\ETL\Transformer;
use Camillebaronnet\ETL\TransformInterface;
class Flatten implements TransformInterface
{
public $rootKey = '';
public $glue = '.';
public $ignore;
public $only;
/**
* The class entry point.
*
* @param array $data
* @return array
*/
public function __invoke(iterable $data): array
{
$flattened = [];
$this->flatten(
$data,
$flattened,
$this->glue,
$this->rootKey
);
return $flattened;
}
/**
* Flatten recursively the data.
*
* @param array $input
* @param array $result
* @param string $glue
* @param string $parentKey
*/
private function flatten(array $input, array &$result, string $glue, string $parentKey = ''): void
{
foreach ($input as $key => $value) {
$only = $this->only
? $this->stringStartBy($parentKey.$key, $this->only)
: true;
$ignore = $this->ignore
? !$this->stringStartBy($parentKey.$key, $this->ignore)
: true;
if (is_array($value) && $only && $ignore) {
$this->flatten($value, $result, $glue, $parentKey.$key.$glue);
} else {
$result[$parentKey.$key] = $value;
}
}
}
/**
* Check if the needle can be found on the haystack.
*
* @param $needle
* @param array $haystack
* @return bool
*/
private function stringStartBy($needle, array $haystack): bool
{
foreach ($haystack as $input) {
if (strpos($needle, $input) === 0) {
return true;
}
}
return false;
}
}