1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Coco\SourceWatcher\Core\Extractors; |
4
|
|
|
|
5
|
|
|
use Coco\SourceWatcher\Core\Extractor; |
6
|
|
|
use Coco\SourceWatcher\Core\Row; |
7
|
|
|
|
8
|
|
|
use Flow\JSONPath\JSONPath; |
9
|
|
|
use Flow\JSONPath\JSONPathException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class JsonExtractor |
13
|
|
|
* @package Coco\SourceWatcher\Core\Extractors |
14
|
|
|
*/ |
15
|
|
|
class JsonExtractor extends Extractor |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
private array $columns = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
protected array $availableOptions = [ "columns" ]; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @return array |
29
|
|
|
*/ |
30
|
|
|
public function getColumns () : array |
31
|
|
|
{ |
32
|
|
|
return $this->columns; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param array $columns |
37
|
|
|
*/ |
38
|
|
|
public function setColumns ( array $columns ) : void |
39
|
|
|
{ |
40
|
|
|
$this->columns = $columns; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return array|mixed |
45
|
|
|
* @throws JSONPathException |
46
|
|
|
*/ |
47
|
|
|
public function extract () |
48
|
|
|
{ |
49
|
|
|
if ( $this->input == null ) { |
50
|
|
|
throw new Exception( "An input must be provided." ); |
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$result = array(); |
54
|
|
|
|
55
|
|
|
// @todo: check if file exists |
56
|
|
|
$data = json_decode( file_get_contents( $this->input ), true ); |
57
|
|
|
|
58
|
|
|
if ( $this->columns ) { |
|
|
|
|
59
|
|
|
// @todo: control possible JSONPathException exception |
60
|
|
|
$jsonPath = new JSONPath( $data ); |
61
|
|
|
|
62
|
|
|
foreach ( $this->columns as $key => $path ) { |
63
|
|
|
$this->columns[$key] = $jsonPath->find( $path )->data(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$data = $this->transpose( $this->columns ); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
foreach ( $data as $row ) { |
70
|
|
|
array_push( $result, new Row( $row ) ); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $result; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param $columns |
78
|
|
|
* @return array |
79
|
|
|
*/ |
80
|
|
|
private function transpose ( $columns ) |
81
|
|
|
{ |
82
|
|
|
$data = []; |
83
|
|
|
|
84
|
|
|
foreach ( $columns as $column => $items ) { |
85
|
|
|
foreach ( $items as $row => $item ) { |
86
|
|
|
$data[$row][$column] = $item; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return $data; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|