generated from spatie/package-skeleton-php
/
QueryResultsDTO.php
80 lines (65 loc) · 2.88 KB
/
QueryResultsDTO.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 ReedTech\AzureDataExplorer\Data;
use Saloon\Http\Response;
class QueryResultsDTO
{
public function __construct(
public array $columns,
public array $data,
public float $executionTime = -1,
) {
}
public static function fromSaloon(Response $response): self
{
$data = $response->json();
// Raw Data Extraction
$rawColumns = $data[2]['Columns'];
$rawRows = $data[2]['Rows'];
$executionTime = null;
try {
$executionTime = json_decode($data[3]['Rows'][2][11])->ExecutionTime;
} catch (\Exception $e) {
$executionTime = json_decode($data[3]['Rows'][3][11])->ExecutionTime;
}
// Morph to intermediate state
$columns = collect($rawColumns)->pluck('ColumnName')->map(function ($column) {
// Column name manipulation
// $column = str_replace('ID', 'Id', $column);
// $column = Str::snake($column);
return trim($column);
})->all();
// Loop through each row and map the column names to the values
$rows = collect($rawRows)->map(function ($row) use ($columns) {
// Loop through each column and map the column name to the value
return collect($row)->map(function ($value, $key) use ($columns) {
// return [$columnName => $value]; // Map the column name to the value
return [$columns[$key] => trim($value)]; // Map the column name to the value
})->collapse()->all(); // Collapse the array to a single level
})->all();
return new static($columns, $rows, $executionTime);
}
public static function parseV1(Response $response): self
{
$data = $response->json();
// Raw Data Extraction
$rawColumns = $data['Tables'][0]['Columns'];
$rawRows = $data['Tables'][0]['Rows'];
// $executionTime = $data['Statistics']['Query']['ExecutionTime'];
// Morph to intermediate state
$columns = collect($rawColumns)->pluck('ColumnName')->map(function ($column) {
// Column name manipulation
// $column = str_replace('ID', 'Id', $column);
// $column = Str::snake($column);
return trim($column);
})->all();
// Loop through each row and map the column names to the values
$rows = collect($rawRows)->map(function ($row) use ($columns) {
// Loop through each column and map the column name to the value
return collect($row)->map(function ($value, $key) use ($columns) {
// return [$columnName => $value]; // Map the column name to the value
return [$columns[$key] => trim($value)]; // Map the column name to the value
})->collapse()->all(); // Collapse the array to a single level
})->all();
return new static($columns, $rows);
}
}