-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathFormatter.php
More file actions
532 lines (469 loc) · 14.4 KB
/
Formatter.php
File metadata and controls
532 lines (469 loc) · 14.4 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
<?php
namespace WP_CLI;
use cli\Colors;
use cli\Table;
use Iterator;
use Mustangostang\Spyc;
use WP_CLI;
/**
* Output one or more items in a given format (e.g. table, JSON).
*
* @property-read string $format
* @property-read string[] $fields
* @property-read string|null $field
* @property-read array<string, int> $alignments
*/
class Formatter {
/**
* Maximum width for a table cell value.
* Values longer than this will be truncated to improve performance.
*
* @var int
*/
const MAX_CELL_WIDTH = 2048;
/**
* How the items should be output.
*
* @var array{format: string, fields: string[], field: string|null, alignments: array<string, int>}
*/
private $args;
/**
* Standard prefix for object fields.
*
* @var string|false
*/
private $prefix;
/**
* @param array $assoc_args Output format arguments.
* @param array $fields Fields to display of each item.
* @param string|false $prefix Check if fields have a standard prefix.
* False indicates empty prefix.
*/
public function __construct( &$assoc_args, $fields = null, $prefix = false ) {
$format_args = [
'format' => 'table',
'fields' => $fields,
'field' => null,
'alignments' => [],
];
foreach ( array_keys( $format_args ) as $key ) {
if ( isset( $assoc_args[ $key ] ) ) {
$format_args[ $key ] = $assoc_args[ $key ];
unset( $assoc_args[ $key ] );
}
}
if ( ! is_array( $format_args['fields'] ) ) {
$format_args['fields'] = explode( ',', $format_args['fields'] );
}
/** @var callable(string): string $trim */
$trim = 'trim';
// @phpstan-ignore argument.type
$format_args['fields'] = array_map( $trim, $format_args['fields'] );
$this->args = $format_args;
$this->prefix = $prefix;
}
/**
* Magic getter for arguments.
*
* @param string $key
* @return mixed
*/
public function __get( $key ) {
return $this->args[ $key ];
}
/**
* Display multiple items according to the output arguments.
*
* @param iterable $items The items to display.
* @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `format()` if items in the table are pre-colorized. Default false.
*/
public function display_items( $items, $ascii_pre_colorized = false ) {
if ( $this->args['field'] ) {
$this->show_single_field( $items, $this->args['field'] );
} else {
// Convert iterator to array early to avoid consumption issues and enable validation
if ( $items instanceof Iterator ) {
$items = iterator_to_array( $items );
}
if ( in_array( $this->args['format'], [ 'csv', 'json', 'table', 'yaml' ], true ) ) {
// Validate fields exist in at least one item
if ( ! empty( $this->args['fields'] ) ) {
$this->validate_fields( $items );
}
}
if ( in_array( $this->args['format'], [ 'table', 'csv' ], true ) ) {
$items = array_map( [ $this, 'transform_item_values_to_json' ], (array) $items );
}
$this->format( $items, $ascii_pre_colorized );
}
}
/**
* Display a single item according to the output arguments.
*
* @param mixed $item
* @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_multiple_fields()` if the item in the table is pre-colorized. Default false.
*/
public function display_item( $item, $ascii_pre_colorized = false ) {
if ( isset( $this->args['field'] ) ) {
$item = (object) $item;
$key = $this->find_item_key( $item, $this->args['field'], true );
if ( null === $key ) {
WP_CLI::warning( "Field not found in item: {$this->args['field']}." );
$value = null;
} else {
$value = $item->$key;
}
if ( in_array( $this->args['format'], [ 'table', 'csv' ], true ) && ( is_object( $value ) || is_array( $value ) ) ) {
$value = json_encode( $value );
}
WP_CLI::print_value(
$value,
[
'format' => $this->args['format'],
]
);
} else {
/**
* @var array $item
*/
$this->show_multiple_fields( $item, $this->args['format'], $ascii_pre_colorized );
}
}
/**
* Truncate cell values in items for table/CSV output.
*
* @param iterable $items Items to process.
* @param array $fields Fields to truncate.
* @return array Processed items with truncated values.
*/
private function truncate_items( $items, $fields ) {
$truncated = [];
foreach ( $items as $item ) {
$row = Utils\pick_fields( $item, $fields );
// Truncate each field value
foreach ( $row as $key => $value ) {
if ( is_string( $value ) && strlen( $value ) > self::MAX_CELL_WIDTH ) {
$row[ $key ] = substr( $value, 0, self::MAX_CELL_WIDTH ) . '...';
}
}
$truncated[] = $row;
}
return $truncated;
}
/**
* Format items according to arguments.
*
* @param iterable $items Items.
* @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if items in the table are pre-colorized. Default false.
*/
private function format( $items, $ascii_pre_colorized = false ): void {
$fields = $this->args['fields'];
switch ( $this->args['format'] ) {
case 'count':
if ( ! is_array( $items ) ) {
$items = iterator_to_array( $items );
}
echo count( $items );
break;
case 'ids':
if ( ! is_array( $items ) ) {
$items = iterator_to_array( $items );
}
/** @var array<string> $items */
echo implode( ' ', $items );
break;
case 'table':
// Truncate large values before table formatting for performance
if ( ! is_array( $items ) ) {
$items = iterator_to_array( $items );
}
$items = $this->truncate_items( $items, $fields );
$this->show_table( $items, $fields, $ascii_pre_colorized );
break;
case 'csv':
// Truncate large values before CSV output for performance
if ( ! is_array( $items ) ) {
$items = iterator_to_array( $items );
}
$items = $this->truncate_items( $items, $fields );
Utils\write_csv( STDOUT, $items, $fields );
break;
case 'json':
case 'yaml':
$out = [];
foreach ( $items as $item ) {
$out[] = Utils\pick_fields( $item, $fields );
}
if ( 'json' === $this->args['format'] ) {
if ( defined( 'JSON_PARTIAL_OUTPUT_ON_ERROR' ) ) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.json_partial_output_on_errorFound
echo json_encode( $out, JSON_PARTIAL_OUTPUT_ON_ERROR );
} else {
echo json_encode( $out );
}
} elseif ( 'yaml' === $this->args['format'] ) {
echo Spyc::YAMLDump( $out, 2, 0 );
}
break;
default:
WP_CLI::error( 'Invalid format: ' . $this->args['format'] );
}
}
/**
* Show a single field from a list of items.
*
* @param iterable $items Array of objects to show fields from
* @param string $field The field to show
*/
private function show_single_field( $items, $field ): void {
$key = null;
$values = [];
$field_found = false;
$item_count = 0;
foreach ( $items as $item ) {
++$item_count;
$item = (object) $item;
// Resolve the key on first item that has the field
if ( ! $field_found && null === $key ) {
$key = $this->find_item_key( $item, $field, true );
if ( null !== $key ) {
$field_found = true;
}
}
// Get value if key exists
$value = ( null !== $key && isset( $item->$key ) ) ? $item->$key : null;
if ( 'json' === $this->args['format'] ) {
$values[] = $value;
} else {
WP_CLI::print_value(
$value,
[
'format' => $this->args['format'],
]
);
}
}
if ( ! $field_found && $item_count > 0 ) {
WP_CLI::warning( "Field not found in any item: $field." );
}
if ( 'json' === $this->args['format'] ) {
echo json_encode( $values );
}
}
/**
* Validate that requested fields exist in at least one item.
* Warns if a field doesn't exist in any item.
* Also resolves field names to their actual keys (including prefixes).
*
* @param iterable $items Items to validate
*/
private function validate_fields( $items ): void {
// Track which fields have been found and their resolved keys
$fields_to_find = array_flip( $this->args['fields'] );
$resolved_fields = [];
$fields_count = count( $fields_to_find );
$found_count = 0;
$item_count = 0;
// Iterate through items once and check all fields
foreach ( $items as $item ) {
++$item_count;
// Check each field that hasn't been found yet
foreach ( $fields_to_find as $field => $_ ) {
$key = $this->find_item_key( $item, $field, true );
if ( null !== $key ) {
// Store the resolved field name
$resolved_fields[ $field ] = $key;
// Mark this field as found
unset( $fields_to_find[ $field ] );
++$found_count;
// If all fields found, we can stop early
if ( $found_count === $fields_count ) {
break 2;
}
}
}
}
// Update the fields array with resolved field names
foreach ( $this->args['fields'] as &$field ) {
if ( isset( $resolved_fields[ $field ] ) ) {
$field = $resolved_fields[ $field ];
}
}
unset( $field ); // Break the reference to avoid issues with subsequent foreach loops
// Only warn about missing fields if there were items to check
if ( $item_count > 0 ) {
// Warn about any fields that weren't found in any item
foreach ( $fields_to_find as $missing_field => $_ ) {
WP_CLI::warning( "Field not found in any item: $missing_field." );
}
}
}
/**
* Find an object's key.
* If $prefix is set, a key with that prefix will be prioritized.
*
* @param array|object $item
* @param string $field
* @param bool $lenient If true, return null instead of erroring when field is not found.
* @return string|null
*/
private function find_item_key( $item, $field, $lenient = false ) {
foreach ( [ $field, $this->prefix . '_' . $field ] as $maybe_key ) {
if (
( is_object( $item ) && ( property_exists( $item, $maybe_key ) || isset( $item->$maybe_key ) ) ) ||
( is_array( $item ) && array_key_exists( $maybe_key, $item ) )
) {
$key = $maybe_key;
break;
}
}
if ( ! isset( $key ) ) {
if ( $lenient ) {
return null;
}
WP_CLI::error( "Invalid field: $field." );
}
return $key;
}
/**
* Show multiple fields of an object.
*
* @param iterable $data Data to display
* @param string $format Format to display the data in
* @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `show_table()` if the item in the table is pre-colorized. Default false.
*/
private function show_multiple_fields( $data, $format, $ascii_pre_colorized = false ): void {
$true_fields = [];
foreach ( $this->args['fields'] as $field ) {
$key = $this->find_item_key( $data, $field, true );
if ( null === $key ) {
// Field doesn't exist, show warning
WP_CLI::warning( "Field not found in item: $field." );
} else {
$true_fields[] = $key;
}
}
foreach ( $data as $key => $value ) {
if ( ! in_array( $key, $true_fields, true ) ) {
if ( is_array( $data ) ) {
unset( $data[ $key ] );
} elseif ( is_object( $data ) ) {
unset( $data->$key );
}
}
}
$ordered_data = [];
foreach ( $true_fields as $field ) {
$ordered_data[ $field ] = ( ( (array) $data )[ $field ] );
}
switch ( $format ) {
case 'table':
case 'csv':
$rows = $this->assoc_array_to_rows( $ordered_data );
$fields = [ 'Field', 'Value' ];
if ( 'table' === $format ) {
self::show_table( $rows, $fields, $ascii_pre_colorized );
} elseif ( 'csv' === $format ) {
Utils\write_csv( STDOUT, $rows, $fields );
}
break;
case 'yaml':
case 'json':
WP_CLI::print_value(
$ordered_data,
[
'format' => $format,
]
);
break;
default:
WP_CLI::error( 'Invalid format: ' . $format );
}
}
/**
* Show items in a \cli\Table.
*
* @param iterable $items Items.
* @param array $fields Fields.
* @param bool|array $ascii_pre_colorized Optional. A boolean or an array of booleans to pass to `Table::setAsciiPreColorized()` if items in the table are pre-colorized. Default false.
*/
private function show_table( $items, $fields, $ascii_pre_colorized = false ) {
$table = new Table();
$enabled = WP_CLI::get_runner()->in_color();
if ( $enabled ) {
Colors::disable( true );
}
$table->setAsciiPreColorized( $ascii_pre_colorized );
$table->setHeaders( $fields );
$table->setAlignments(
$this->args['alignments']
);
foreach ( $items as $item ) {
$table->addRow( array_values( Utils\pick_fields( $item, $fields ) ) );
}
foreach ( $table->getDisplayLines() as $line ) {
WP_CLI::line( $line );
}
if ( $enabled ) {
Colors::enable( true );
}
}
/**
* Format an associative array as a table.
*
* @param iterable $fields Fields and values to format
* @return array
*/
private function assoc_array_to_rows( $fields ) {
$rows = [];
foreach ( $fields as $field => $value ) {
if ( ! is_string( $value ) ) {
$value = json_encode( $value );
}
// Truncate large values for table/CSV output performance
if ( is_string( $value ) && strlen( $value ) > self::MAX_CELL_WIDTH ) {
$value = substr( $value, 0, self::MAX_CELL_WIDTH ) . '...';
}
$rows[] = (object) [
'Field' => $field,
'Value' => $value,
];
}
return $rows;
}
/**
* Transforms item values for string-based output formats (table/CSV).
*
* Converts complex types to strings:
* - Objects and arrays are converted to JSON strings
* - Booleans are converted to "true" or "false"
*
* @param array|object $item
* @return mixed
*/
public function transform_item_values_to_json( $item ) {
foreach ( $this->args['fields'] as $field ) {
$true_field = $this->find_item_key( $item, $field, true );
if ( null === $true_field ) {
// Field doesn't exist in this item, skip it
continue;
}
$value = is_object( $item ) ? $item->$true_field : $item[ $true_field ];
if ( is_array( $value ) || is_object( $value ) ) {
if ( is_object( $item ) ) {
$item->$true_field = json_encode( $value );
} elseif ( is_array( $item ) ) {
$item[ $true_field ] = json_encode( $value );
}
} elseif ( is_bool( $value ) ) {
// Convert boolean to string representation for table/CSV display
if ( is_object( $item ) ) {
$item->$true_field = $value ? 'true' : 'false';
} elseif ( is_array( $item ) ) {
$item[ $true_field ] = $value ? 'true' : 'false';
}
}
}
return $item;
}
}