-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOutput_Style.php
More file actions
89 lines (71 loc) · 2.17 KB
/
Copy pathOutput_Style.php
File metadata and controls
89 lines (71 loc) · 2.17 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
<?php
/**
* Output_Style class file
*
* @package Mantle
*/
declare(strict_types=1);
namespace Mantle\Console;
use Symfony\Component\Console\Style\SymfonyStyle;
use function Mantle\Support\Helpers\collect;
/**
* Output Style
*/
class Output_Style extends SymfonyStyle {
/**
* Format JSON for output.
*
* @param array<mixed> $headers Headers for the data.
* @param array<mixed> $data Data with no keys.
*/
public function format_json( array $headers, array $data ): void {
// Merge the headers with the data.
$data = collect( $data )
->map( fn ( $row ) => array_combine( $headers, $row ) )
->to_array();
$this->write( (string) json_encode( $data, JSON_PRETTY_PRINT ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
}
/**
* Format data for output in a CSV.
*
* @param array<mixed> $headers Headers for the data.
* @param array<mixed> $data Data with no keys.
*/
public function format_csv( array $headers, array $data ): void {
// Merge the headers with the data.
$data = collect( $data )
->map( fn ( $row ) => array_combine( $headers, $row ) )
->to_array();
// todo: update to write to output.
$fp = fopen( 'php://output', 'wb' );
if ( ! $fp ) {
$this->error( 'Failed to open output stream for writing.' );
return;
}
fputcsv( $fp, $headers ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fputcsv
foreach ( $data as $row ) {
fputcsv( $fp, $row ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.file_ops_fputcsv
}
fclose( $fp );
}
/**
* Format data for output in XML format.
*
* @param array<mixed> $headers Headers for the data.
* @param array<mixed> $data Data with no keys.
*/
public function format_xml( array $headers, array $data ): void {
// Merge the headers with the data.
$data = collect( $data )
->map( fn ( $row ) => array_combine( $headers, $row ) )
->to_array();
$xml = new \SimpleXMLElement( '<root/>' );
foreach ( $data as $row ) {
$item = $xml->addChild( 'item' );
foreach ( $row as $key => $value ) {
$item->addChild( $key, (string) $value );
}
}
$this->write( (string) $xml->asXML() );
}
}