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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
|
//! ref: composer/vendor/symfony/console/Helper/Table.php
use crate::composer::pcre::preg::Preg;
use crate::symfony::console::exception::invalid_argument_exception::InvalidArgumentException;
use crate::symfony::console::exception::runtime_exception::RuntimeException;
use crate::symfony::console::formatter::output_formatter::OutputFormatter;
use crate::symfony::console::formatter::wrappable_output_formatter_interface::WrappableOutputFormatterInterface;
use crate::symfony::console::helper::helper::Helper;
use crate::symfony::console::helper::table_cell::{TableCell, TableCellOption};
use crate::symfony::console::helper::table_cell_style::TableCellStyle;
use crate::symfony::console::helper::table_rows::TableRows;
use crate::symfony::console::helper::table_separator::TableSeparator;
use crate::symfony::console::helper::table_style::TableStyle;
use crate::symfony::console::output::console_section_output::ConsoleSectionOutput;
use crate::symfony::console::output::output_interface::OutputInterface;
use indexmap::IndexMap;
use shirabe_php_shim::PhpMixed;
use std::cell::RefCell;
use std::rc::Rc;
/// Provides helpers to display a table.
#[derive(Debug)]
pub struct Table {
header_title: Option<String>,
footer_title: Option<String>,
/// Table headers.
headers: Vec<PhpMixed>,
/// Table rows.
rows: Vec<PhpMixed>,
horizontal: bool,
/// Column widths cache.
effective_column_widths: IndexMap<i64, i64>,
/// Number of columns cache.
number_of_columns: Option<i64>,
output: Rc<RefCell<dyn OutputInterface>>,
style: TableStyle,
column_styles: IndexMap<i64, TableStyle>,
/// User set column widths.
column_widths: IndexMap<i64, i64>,
column_max_widths: IndexMap<i64, i64>,
rendered: bool,
}
const SEPARATOR_TOP: i64 = 0;
const SEPARATOR_TOP_BOTTOM: i64 = 1;
const SEPARATOR_MID: i64 = 2;
const SEPARATOR_BOTTOM: i64 = 3;
const BORDER_OUTSIDE: i64 = 0;
const BORDER_INSIDE: i64 = 1;
/// Global style definitions, lazily initialized.
///
/// In PHP this is `private static $styles`. Here it is a process-global cache.
fn styles() -> &'static std::sync::Mutex<Option<IndexMap<String, TableStyle>>> {
static STYLES: std::sync::Mutex<Option<IndexMap<String, TableStyle>>> =
std::sync::Mutex::new(None);
&STYLES
}
impl Table {
pub fn new(output: Rc<RefCell<dyn OutputInterface>>) -> Self {
let mut styles_guard = styles().lock().unwrap();
if styles_guard.is_none() {
*styles_guard = Some(Self::init_styles());
}
drop(styles_guard);
let mut this = Self {
header_title: None,
footer_title: None,
headers: Vec::new(),
rows: Vec::new(),
horizontal: false,
effective_column_widths: IndexMap::new(),
number_of_columns: None,
output,
style: TableStyle::default(),
column_styles: IndexMap::new(),
column_widths: IndexMap::new(),
column_max_widths: IndexMap::new(),
rendered: false,
};
this.set_style(PhpMixed::from("default"));
this
}
/// Sets a style definition.
pub fn set_style_definition(name: String, style: TableStyle) {
let mut styles_guard = styles().lock().unwrap();
if styles_guard.is_none() {
*styles_guard = Some(Self::init_styles());
}
styles_guard.as_mut().unwrap().insert(name, style);
}
/// Gets a style definition by name.
pub fn get_style_definition(
name: String,
) -> anyhow::Result<Result<TableStyle, InvalidArgumentException>> {
let mut styles_guard = styles().lock().unwrap();
if styles_guard.is_none() {
*styles_guard = Some(Self::init_styles());
}
if let Some(_style) = styles_guard.as_ref().unwrap().get(&name) {
// TODO(phase-b): TableStyle is not Clone; sharing semantics need resolving.
todo!()
}
Ok(Err(InvalidArgumentException(
shirabe_php_shim::InvalidArgumentException {
message: format!("Style \"{}\" is not defined.", name),
code: 0,
},
)))
}
/// Sets table style.
///
/// `$name` is the style name or a TableStyle instance.
pub fn set_style(
&mut self,
name: PhpMixed,
) -> anyhow::Result<Result<&mut Self, InvalidArgumentException>> {
match self.resolve_style(name)? {
Ok(style) => {
self.style = style;
Ok(Ok(self))
}
Err(e) => Ok(Err(e)),
}
}
/// Gets the current table style.
pub fn get_style(&self) -> &TableStyle {
&self.style
}
/// Sets table column style.
///
/// `$name` is the style name or a TableStyle instance.
pub fn set_column_style(
&mut self,
column_index: i64,
name: PhpMixed,
) -> anyhow::Result<Result<&mut Self, InvalidArgumentException>> {
match self.resolve_style(name)? {
Ok(style) => {
self.column_styles.insert(column_index, style);
Ok(Ok(self))
}
Err(e) => Ok(Err(e)),
}
}
/// Gets the current style for a column.
///
/// If style was not set, it returns the global table style.
pub fn get_column_style(&self, column_index: i64) -> &TableStyle {
self.column_styles
.get(&column_index)
.unwrap_or_else(|| self.get_style())
}
/// Sets the minimum width of a column.
pub fn set_column_width(&mut self, column_index: i64, width: i64) -> &mut Self {
self.column_widths.insert(column_index, width);
self
}
/// Sets the minimum width of all columns.
pub fn set_column_widths(&mut self, widths: Vec<i64>) -> &mut Self {
self.column_widths = IndexMap::new();
for (index, width) in widths.into_iter().enumerate() {
self.set_column_width(index as i64, width);
}
self
}
/// Sets the maximum width of a column.
///
/// Any cell within this column which contents exceeds the specified width will be wrapped into
/// multiple lines, while formatted strings are preserved.
pub fn set_column_max_width(&mut self, column_index: i64, width: i64) -> &mut Self {
if !Self::formatter_is_wrappable(&self.output) {
// PHP throws \LogicException here. This represents a programming error: the caller must
// supply a WrappableOutputFormatterInterface before setting a maximum column width.
panic!(
"Setting a maximum column width is only supported when using a \"{}\" formatter, got \"{}\".",
"Symfony\\Component\\Console\\Formatter\\WrappableOutputFormatterInterface",
shirabe_php_shim::get_debug_type(&PhpMixed::from(()))
);
}
self.column_max_widths.insert(column_index, width);
self
}
pub fn set_headers(&mut self, headers: Vec<PhpMixed>) -> &mut Self {
// PHP: $headers = array_values($headers). A row is already modeled as a positional Vec,
// so reindexing is the identity here.
let mut headers = headers;
if !headers.is_empty() && !shirabe_php_shim::is_array(&headers[0]) {
headers = vec![Self::from_row_vec(headers)];
}
self.headers = headers;
self
}
pub fn set_rows(&mut self, rows: Vec<PhpMixed>) -> &mut Self {
self.rows = Vec::new();
self.add_rows(rows)
}
pub fn add_rows(&mut self, rows: Vec<PhpMixed>) -> &mut Self {
for row in rows {
self.add_row(row);
}
self
}
pub fn add_row(
&mut self,
row: PhpMixed,
) -> anyhow::Result<Result<&mut Self, InvalidArgumentException>> {
if shirabe_php_shim::instance_of::<TableSeparator>(&row) {
self.rows.push(row);
return Ok(Ok(self));
}
if !shirabe_php_shim::is_array(&row) {
return Ok(Err(InvalidArgumentException(
shirabe_php_shim::InvalidArgumentException {
message: "A row must be an array or a TableSeparator instance.".to_string(),
code: 0,
},
)));
}
// PHP: $this->rows[] = array_values($row). The row is modeled as a positional Vec.
self.rows.push(Self::from_row_vec(Self::to_row_vec(row)));
Ok(Ok(self))
}
/// Adds a row to the table, and re-renders the table.
pub fn append_row(
&mut self,
row: PhpMixed,
) -> anyhow::Result<Result<&mut Self, RuntimeException>> {
if !Self::output_is_console_section(&self.output) {
return Ok(Err(RuntimeException(shirabe_php_shim::RuntimeException {
message: format!(
"Output should be an instance of \"{}\" when calling \"{}\".",
"Symfony\\Component\\Console\\Output\\ConsoleSectionOutput",
"Symfony\\Component\\Console\\Helper\\Table::appendRow",
),
code: 0,
})));
}
if self.rendered {
// TODO(phase-b): downcast output to ConsoleSectionOutput to call clear().
let _ = ConsoleSectionOutput::clear;
let row_count = self.calculate_row_count();
let _ = row_count;
todo!()
}
self.add_row(row)?.ok();
self.render();
Ok(Ok(self))
}
pub fn set_row(&mut self, column: i64, row: Vec<PhpMixed>) -> &mut Self {
// PHP indexes $this->rows by arbitrary key; here we follow the integer-keyed case.
let _ = (column, row);
todo!()
}
pub fn set_header_title(&mut self, title: Option<String>) -> &mut Self {
self.header_title = title;
self
}
pub fn set_footer_title(&mut self, title: Option<String>) -> &mut Self {
self.footer_title = title;
self
}
pub fn set_horizontal(&mut self, horizontal: bool) -> &mut Self {
self.horizontal = horizontal;
self
}
/// Renders table to output.
pub fn render(&mut self) {
let divider = TableSeparator::new();
let rows: Vec<PhpMixed>;
if self.horizontal {
let mut horizontal_rows: IndexMap<i64, Vec<PhpMixed>> = IndexMap::new();
let header0 = self
.headers
.first()
.map(|h| Self::to_row_vec(h.clone()))
.unwrap_or_default();
for (i, header) in header0.into_iter().enumerate() {
let i = i as i64;
horizontal_rows.insert(i, vec![header]);
for row in &self.rows {
if shirabe_php_shim::instance_of::<TableSeparator>(row) {
continue;
}
if let Some(cell) = Self::row_get(row, i) {
let entry = horizontal_rows.get_mut(&i).unwrap();
entry.push(cell);
} else {
let first = horizontal_rows.get(&i).unwrap().first().cloned();
let is_title_noop = match first {
Some(ref c) if shirabe_php_shim::instance_of::<TableCell>(c) => {
Self::cell_colspan(c) >= 2
}
_ => false,
};
if is_title_noop {
// Noop, there is a "title"
} else {
let entry = horizontal_rows.get_mut(&i).unwrap();
entry.push(PhpMixed::from(()));
}
}
}
}
rows = horizontal_rows
.into_values()
.map(Self::from_row_vec)
.collect();
} else {
let mut merged = self.headers.clone();
merged.push(Self::table_separator_to_mixed(divider.clone()));
merged.extend(self.rows.clone());
rows = merged;
}
self.calculate_number_of_columns(&rows);
let row_groups = self.build_table_rows(rows);
self.calculate_columns_width(&row_groups);
let mut is_header = !self.horizontal;
let mut is_first_row = self.horizontal;
let mut has_title =
self.header_title.is_some() && !self.header_title.as_deref().unwrap_or("").is_empty();
for row_group in &row_groups {
let mut is_header_separator_rendered = false;
for row in row_group {
if Self::is_divider(row, ÷r) {
is_header = false;
is_first_row = true;
continue;
}
if shirabe_php_shim::instance_of::<TableSeparator>(row) {
self.render_row_separator(SEPARATOR_MID, None, None);
continue;
}
if !shirabe_php_shim::to_bool(row) {
continue;
}
if is_header && !is_header_separator_rendered {
self.render_row_separator(
if is_header {
SEPARATOR_TOP
} else {
SEPARATOR_TOP_BOTTOM
},
if has_title {
self.header_title.clone()
} else {
None
},
if has_title {
Some(self.style.get_header_title_format())
} else {
None
},
);
has_title = false;
is_header_separator_rendered = true;
}
if is_first_row {
self.render_row_separator(
if is_header {
SEPARATOR_TOP
} else {
SEPARATOR_TOP_BOTTOM
},
if has_title {
self.header_title.clone()
} else {
None
},
if has_title {
Some(self.style.get_header_title_format())
} else {
None
},
);
is_first_row = false;
has_title = false;
}
if self.horizontal {
self.render_row(
Self::to_row_vec(row.clone()),
self.style.get_cell_row_format(),
Some(self.style.get_cell_header_format()),
);
} else {
self.render_row(
Self::to_row_vec(row.clone()),
if is_header {
self.style.get_cell_header_format()
} else {
self.style.get_cell_row_format()
},
None,
);
}
}
}
self.render_row_separator(
SEPARATOR_BOTTOM,
self.footer_title.clone(),
Some(self.style.get_footer_title_format()),
);
self.cleanup();
self.rendered = true;
}
/// Renders horizontal header separator.
fn render_row_separator(
&self,
r#type: i64,
title: Option<String>,
title_format: Option<String>,
) {
let count = match self.number_of_columns {
Some(0) | None => return,
Some(c) => c,
};
let borders = self.style.get_border_chars();
if borders[0].is_empty()
&& borders[2].is_empty()
&& self.style.get_crossing_char().is_empty()
{
return;
}
let crossings = self.style.get_crossing_chars();
let (horizontal, left_char, mid_char, right_char) = if SEPARATOR_MID == r#type {
(
borders[2].clone(),
crossings[8].clone(),
crossings[0].clone(),
crossings[4].clone(),
)
} else if SEPARATOR_TOP == r#type {
(
borders[0].clone(),
crossings[1].clone(),
crossings[2].clone(),
crossings[3].clone(),
)
} else if SEPARATOR_TOP_BOTTOM == r#type {
(
borders[0].clone(),
crossings[9].clone(),
crossings[10].clone(),
crossings[11].clone(),
)
} else {
(
borders[0].clone(),
crossings[7].clone(),
crossings[6].clone(),
crossings[5].clone(),
)
};
let mut markup = left_char;
let mut column = 0;
while column < count {
markup.push_str(&shirabe_php_shim::str_repeat(
&horizontal,
self.effective_column_widths[&column] as usize,
));
markup.push_str(if column == count - 1 {
&right_char
} else {
&mid_char
});
column += 1;
}
if let Some(title) = title {
let title_format = title_format.unwrap();
let formatted_title =
shirabe_php_shim::sprintf(&title_format, &[PhpMixed::from(title.clone())]);
let mut formatted_title = formatted_title;
let mut title_length = Helper::width(&self.remove_decoration(&formatted_title));
let markup_length = Helper::width(&markup);
let limit = markup_length - 4;
if title_length > limit {
title_length = limit;
let format_length = Helper::width(&self.remove_decoration(
&shirabe_php_shim::sprintf(&title_format, &[PhpMixed::from("")]),
));
formatted_title = shirabe_php_shim::sprintf(
&title_format,
&[PhpMixed::from(format!(
"{}...",
Helper::substr(&title, 0, Some(limit - format_length - 3))
))],
);
}
let title_start = (markup_length - title_length) / 2;
if shirabe_php_shim::mb_detect_encoding(&markup, None, true).is_none() {
markup = shirabe_php_shim::substr_replace(
&markup,
&formatted_title,
title_start as usize,
title_length as usize,
);
} else {
markup = format!(
"{}{}{}",
shirabe_php_shim::mb_substr(&markup, 0, Some(title_start), None),
formatted_title,
shirabe_php_shim::mb_substr(&markup, title_start + title_length, None, None),
);
}
}
self.output.borrow().writeln(
&[shirabe_php_shim::sprintf(
&self.style.get_border_format(),
&[PhpMixed::from(markup)],
)],
crate::symfony::console::output::output_interface::OUTPUT_NORMAL,
);
}
/// Renders vertical column separator.
fn render_column_separator(&self, r#type: i64) -> String {
let borders = self.style.get_border_chars();
shirabe_php_shim::sprintf(
&self.style.get_border_format(),
&[PhpMixed::from(if BORDER_OUTSIDE == r#type {
borders[1].clone()
} else {
borders[3].clone()
})],
)
}
/// Renders table row.
fn render_row(
&self,
row: Vec<PhpMixed>,
cell_format: String,
first_cell_format: Option<String>,
) {
let mut row_content = self.render_column_separator(BORDER_OUTSIDE);
let columns = self.get_row_columns(&row);
let last = columns.len() as i64 - 1;
for (i, column) in columns.into_iter().enumerate() {
let i = i as i64;
if first_cell_format.is_some() && 0 == i {
row_content.push_str(&self.render_cell(
&row,
column,
first_cell_format.clone().unwrap(),
));
} else {
row_content.push_str(&self.render_cell(&row, column, cell_format.clone()));
}
row_content.push_str(&self.render_column_separator(if last == i {
BORDER_OUTSIDE
} else {
BORDER_INSIDE
}));
}
self.output.borrow().writeln(
&[row_content],
crate::symfony::console::output::output_interface::OUTPUT_NORMAL,
);
}
/// Renders table cell with padding.
fn render_cell(&self, row: &[PhpMixed], column: i64, cell_format: String) -> String {
let cell = Self::row_get_index(row, column).unwrap_or_else(|| PhpMixed::from(""));
let mut width = self.effective_column_widths[&column];
if shirabe_php_shim::instance_of::<TableCell>(&cell) && Self::cell_colspan(&cell) > 1 {
// add the width of the following columns(numbers of colspan).
for next_column in (column + 1)..=(column + Self::cell_colspan(&cell) - 1) {
width +=
self.get_column_separator_width() + self.effective_column_widths[&next_column];
}
}
// str_pad won't work properly with multi-byte strings, we need to fix the padding
let cell_str = shirabe_php_shim::to_string(&cell);
if let Some(encoding) = shirabe_php_shim::mb_detect_encoding(&cell_str, None, true) {
width += shirabe_php_shim::strlen(&cell_str)
- shirabe_php_shim::mb_strwidth(&cell_str, Some(&encoding));
}
let style = self.get_column_style(column);
if shirabe_php_shim::instance_of::<TableSeparator>(&cell) {
return shirabe_php_shim::sprintf(
&style.get_border_format(),
&[PhpMixed::from(shirabe_php_shim::str_repeat(
&style.get_border_chars()[2],
width as usize,
))],
);
}
width += Helper::length(&cell_str) - Helper::length(&self.remove_decoration(&cell_str));
let mut content = shirabe_php_shim::sprintf(
&style.get_cell_row_content_format(),
&[PhpMixed::from(cell_str.clone())],
);
let mut cell_format = cell_format;
let mut pad_type = style.get_pad_type();
if shirabe_php_shim::instance_of::<TableCell>(&cell)
&& Self::cell_style_is_table_cell_style(&cell)
{
let is_not_styled_by_tag = !Preg::is_match(
"/^<(\\w+|(\\w+=[\\w,]+;?)*)>.+<\\/(\\w+|(\\w+=\\w+;?)*)?>$/",
&cell_str,
);
if is_not_styled_by_tag {
let cell_style = Self::cell_get_style(&cell).unwrap();
match cell_style.get_cell_format() {
Some(fmt) => cell_format = fmt,
None => {
let tag = shirabe_php_shim::http_build_query_mixed(
&cell_style.get_tag_options(),
"",
";",
);
cell_format = format!("<{}>%s</>", tag);
}
}
if shirabe_php_shim::strstr(&content, "</>").is_some() {
content = shirabe_php_shim::str_replace("</>", "", &content);
width -= 3;
}
if shirabe_php_shim::strstr(&content, "<fg=default;bg=default>").is_some() {
content =
shirabe_php_shim::str_replace("<fg=default;bg=default>", "", &content);
width -= shirabe_php_shim::strlen("<fg=default;bg=default>");
}
}
pad_type = Self::cell_get_style(&cell).unwrap().get_pad_by_align();
}
shirabe_php_shim::sprintf(
&cell_format,
&[PhpMixed::from(shirabe_php_shim::str_pad(
&content,
width as usize,
&style.get_padding_char(),
pad_type,
))],
)
}
/// Calculate number of columns for this table.
fn calculate_number_of_columns(&mut self, rows: &[PhpMixed]) {
let mut columns = vec![0i64];
for row in rows {
if shirabe_php_shim::instance_of::<TableSeparator>(row) {
continue;
}
columns.push(self.get_number_of_columns(&Self::to_row_vec(row.clone())));
}
self.number_of_columns = Some(*columns.iter().max().unwrap());
}
fn build_table_rows(&mut self, rows: Vec<PhpMixed>) -> TableRows {
let mut rows = rows;
let mut unmerged_rows: IndexMap<i64, IndexMap<i64, Vec<PhpMixed>>> = IndexMap::new();
let mut row_key = 0i64;
while row_key < rows.len() as i64 {
rows = self.fill_next_rows(rows, row_key);
// Remove any new line breaks and replace it with a new line
let current = Self::to_row_vec(rows[row_key as usize].clone());
for (column, cell) in current.iter().enumerate() {
let column = column as i64;
let mut cell = cell.clone();
let colspan = if shirabe_php_shim::instance_of::<TableCell>(&cell) {
Self::cell_colspan(&cell)
} else {
1
};
if self.column_max_widths.contains_key(&column)
&& Helper::width(&self.remove_decoration(&shirabe_php_shim::to_string(&cell)))
> self.column_max_widths[&column]
{
// TODO(phase-b): formatAndWrap requires a WrappableOutputFormatterInterface;
// downcasting dyn OutputFormatterInterface to it needs concrete knowledge.
let _ = colspan;
let wrapped: Option<String> = todo!();
cell = PhpMixed::from(wrapped.unwrap_or_default());
}
let cell_str = shirabe_php_shim::to_string(&cell);
if shirabe_php_shim::strstr(&cell_str, "\n").is_none() {
continue;
}
let eol = if shirabe_php_shim::str_contains(&cell_str, "\r\n") {
"\r\n"
} else {
"\n"
};
let escaped = shirabe_php_shim::implode(
eol,
&shirabe_php_shim::explode(eol, &cell_str)
.iter()
.map(|line| OutputFormatter::escape_trailing_backslash(line))
.collect::<Vec<_>>(),
);
cell = if shirabe_php_shim::instance_of::<TableCell>(&cell) {
Self::table_cell_to_mixed(TableCell::new2(
&escaped,
Self::table_cell_options_colspan(Self::cell_colspan(&cell)),
))
} else {
PhpMixed::from(escaped.clone())
};
let lines = shirabe_php_shim::explode(
eol,
&shirabe_php_shim::str_replace(
eol,
&format!("<fg=default;bg=default></>{}", eol),
&shirabe_php_shim::to_string(&cell),
),
);
for (line_key, line) in lines.into_iter().enumerate() {
let line_key = line_key as i64;
let mut line = PhpMixed::from(line);
if colspan > 1 {
line = Self::table_cell_to_mixed(TableCell::new2(
&shirabe_php_shim::to_string(&line),
Self::table_cell_options_colspan(colspan),
));
}
if 0 == line_key {
let mut r = Self::to_row_vec(rows[row_key as usize].clone());
Self::array_set(&mut r, column, line);
rows[row_key as usize] = Self::from_row_vec(r);
} else {
if !unmerged_rows.contains_key(&row_key)
|| !unmerged_rows[&row_key].contains_key(&line_key)
{
let copied = self.copy_row(&rows, row_key);
unmerged_rows
.entry(row_key)
.or_default()
.insert(line_key, copied);
}
let target = unmerged_rows
.get_mut(&row_key)
.unwrap()
.get_mut(&line_key)
.unwrap();
Self::vec_set(target, column, line);
}
}
}
row_key += 1;
}
// PHP returns a TableRows wrapping a generator that lazily yields row groups.
// The generator borrows $this to call fillCells(). In Phase A we precompute the
// row groups eagerly to preserve behavior, then hand them to TableRows.
let mut row_groups: Vec<Vec<PhpMixed>> = Vec::new();
for (row_key, row) in rows.into_iter().enumerate() {
let row_key = row_key as i64;
let mut row_group: Vec<PhpMixed> =
vec![if shirabe_php_shim::instance_of::<TableSeparator>(&row) {
row
} else {
Self::from_row_vec(self.fill_cells(Self::to_row_vec(row)))
}];
if let Some(extra) = unmerged_rows.get(&row_key) {
for r in extra.values() {
let r = Self::from_row_vec(r.clone());
row_group.push(if shirabe_php_shim::instance_of::<TableSeparator>(&r) {
r
} else {
Self::from_row_vec(self.fill_cells(Self::to_row_vec(r)))
});
}
}
row_groups.push(row_group);
}
TableRows::from_row_groups(row_groups)
}
fn calculate_row_count(&mut self) -> i64 {
let mut merged = self.headers.clone();
merged.push(Self::table_separator_to_mixed(TableSeparator::new()));
merged.extend(self.rows.clone());
let mut number_of_rows =
shirabe_php_shim::iterator_to_array(self.build_table_rows(merged)).len() as i64;
if !self.headers.is_empty() {
number_of_rows += 1; // Add row for header separator
}
if !self.rows.is_empty() {
number_of_rows += 1; // Add row for footer separator
}
number_of_rows
}
/// fill rows that contains rowspan > 1.
fn fill_next_rows(&self, rows: Vec<PhpMixed>, line: i64) -> Vec<PhpMixed> {
let mut rows = rows;
let mut unmerged_rows: IndexMap<i64, IndexMap<i64, PhpMixed>> = IndexMap::new();
let current = Self::to_row_vec(rows[line as usize].clone());
for (column, cell) in current.iter().enumerate() {
let column = column as i64;
let cell = cell.clone();
if !shirabe_php_shim::is_null(&cell)
&& !shirabe_php_shim::instance_of::<TableCell>(&cell)
&& !shirabe_php_shim::is_scalar(&cell)
&& !(shirabe_php_shim::is_object(&cell)
&& shirabe_php_shim::method_exists(&cell, "__toString"))
{
// PHP throws InvalidArgumentException; the @throws contract makes this a
// recoverable error. In Phase A we keep the panic placeholder as fill_next_rows
// does not yet return a Result in the call chain.
// TODO(phase-b): thread InvalidArgumentException through fill_next_rows.
panic!(
"A cell must be a TableCell, a scalar or an object implementing \"__toString()\", \"{}\" given.",
shirabe_php_shim::get_debug_type(&cell)
);
}
if shirabe_php_shim::instance_of::<TableCell>(&cell) && Self::cell_rowspan(&cell) > 1 {
let mut nb_lines = Self::cell_rowspan(&cell) - 1;
let cell_str = shirabe_php_shim::to_string(&cell);
let mut lines = vec![cell.clone()];
if shirabe_php_shim::strstr(&cell_str, "\n").is_some() {
let eol = if shirabe_php_shim::str_contains(&cell_str, "\r\n") {
"\r\n"
} else {
"\n"
};
let exploded = shirabe_php_shim::explode(
eol,
&shirabe_php_shim::str_replace(
eol,
&format!("<fg=default;bg=default>{}</>", eol),
&cell_str,
),
);
lines = exploded.into_iter().map(PhpMixed::from).collect();
nb_lines = if (lines.len() as i64) > nb_lines {
shirabe_php_shim::substr_count(&cell_str, eol)
} else {
nb_lines
};
let mut r = Self::to_row_vec(rows[line as usize].clone());
Self::array_set(
&mut r,
column,
Self::table_cell_to_mixed(TableCell::new2(
&shirabe_php_shim::to_string(&lines[0]),
Self::table_cell_options_colspan_style(
Self::cell_colspan(&cell),
Self::cell_get_style(&cell),
),
)),
);
rows[line as usize] = Self::from_row_vec(r);
lines.remove(0);
}
// create a two dimensional array (rowspan x colspan)
for k in (line + 1)..=(line + nb_lines) {
unmerged_rows.entry(k).or_default();
}
for unmerged_row_key in unmerged_rows.keys().cloned().collect::<Vec<_>>() {
let idx = unmerged_row_key - line;
let value = lines
.get(idx as usize)
.cloned()
.unwrap_or_else(|| PhpMixed::from(""));
unmerged_rows.get_mut(&unmerged_row_key).unwrap().insert(
column,
Self::table_cell_to_mixed(TableCell::new2(
&shirabe_php_shim::to_string(&value),
Self::table_cell_options_colspan_style(
Self::cell_colspan(&cell),
Self::cell_get_style(&cell),
),
)),
);
if nb_lines == unmerged_row_key - line {
break;
}
}
}
}
for (unmerged_row_key, unmerged_row) in unmerged_rows.clone() {
// we need to know if $unmergedRow will be merged or inserted into $rows
let fits = (unmerged_row_key as usize) < rows.len()
&& shirabe_php_shim::is_array(&rows[unmerged_row_key as usize])
&& (self.get_number_of_columns(&Self::to_row_vec(
rows[unmerged_row_key as usize].clone(),
)) + self.get_number_of_columns(
&unmerged_rows[&unmerged_row_key]
.values()
.cloned()
.collect::<Vec<_>>(),
) <= self.number_of_columns.unwrap());
if fits {
let mut target = Self::to_row_vec(rows[unmerged_row_key as usize].clone());
for (cell_key, cell) in unmerged_row {
// insert cell into row at cellKey position
shirabe_php_shim::array_splice(&mut target, cell_key, Some(0), vec![cell]);
}
rows[unmerged_row_key as usize] = Self::from_row_vec(target);
} else {
let mut row = self.copy_row(&rows, unmerged_row_key - 1);
for (column, cell) in &unmerged_row {
if shirabe_php_shim::to_bool(cell) {
Self::vec_set(&mut row, *column, unmerged_row[column].clone());
}
}
shirabe_php_shim::array_splice(
&mut rows,
unmerged_row_key,
Some(0),
vec![Self::from_row_vec(row)],
);
}
}
rows
}
/// fill cells for a row that contains colspan > 1.
fn fill_cells(&self, row: Vec<PhpMixed>) -> Vec<PhpMixed> {
let mut new_row: Vec<PhpMixed> = Vec::new();
for (column, cell) in row.iter().enumerate() {
let column = column as i64;
new_row.push(cell.clone());
if shirabe_php_shim::instance_of::<TableCell>(cell) && Self::cell_colspan(cell) > 1 {
for _position in (column + 1)..=(column + Self::cell_colspan(cell) - 1) {
// insert empty value at column position
new_row.push(PhpMixed::from(""));
}
}
}
if new_row.is_empty() { row } else { new_row }
}
fn copy_row(&self, rows: &[PhpMixed], line: i64) -> Vec<PhpMixed> {
let mut row = Self::to_row_vec(rows[line as usize].clone());
for cell in &mut row {
let cell_value = cell.clone();
*cell = PhpMixed::from("");
if shirabe_php_shim::instance_of::<TableCell>(&cell_value) {
*cell = Self::table_cell_to_mixed(TableCell::new2(
"",
Self::table_cell_options_colspan(Self::cell_colspan(&cell_value)),
));
}
}
row
}
/// Gets number of columns by row.
fn get_number_of_columns(&self, row: &[PhpMixed]) -> i64 {
let mut columns = row.len() as i64;
for column in row {
columns += if shirabe_php_shim::instance_of::<TableCell>(column) {
Self::cell_colspan(column) - 1
} else {
0
};
}
columns
}
/// Gets list of columns for the given row.
fn get_row_columns(&self, row: &[PhpMixed]) -> Vec<i64> {
let mut columns: Vec<i64> = (0..self.number_of_columns.unwrap()).collect();
for (cell_key, cell) in row.iter().enumerate() {
let cell_key = cell_key as i64;
if shirabe_php_shim::instance_of::<TableCell>(cell) && Self::cell_colspan(cell) > 1 {
// exclude grouped columns.
let excluded: Vec<i64> =
((cell_key + 1)..=(cell_key + Self::cell_colspan(cell) - 1)).collect();
columns.retain(|c| !excluded.contains(c));
}
}
columns
}
/// Calculates columns widths.
fn calculate_columns_width(&mut self, groups: &TableRows) {
let mut column = 0;
while column < self.number_of_columns.unwrap() {
let mut lengths: Vec<i64> = Vec::new();
for group in groups {
for row in group {
if shirabe_php_shim::instance_of::<TableSeparator>(row) {
continue;
}
let mut row_arr = Self::to_row_vec(row.clone());
for i in 0..row_arr.len() {
let cell = row_arr[i].clone();
if shirabe_php_shim::instance_of::<TableCell>(&cell) {
let text_content =
self.remove_decoration(&shirabe_php_shim::to_string(&cell));
let text_length = Helper::width(&text_content);
if text_length > 0 {
let content_columns = shirabe_php_shim::mb_str_split(
&text_content,
(text_length as f64 / Self::cell_colspan(&cell) as f64).ceil()
as i64,
);
for (position, content) in content_columns.into_iter().enumerate() {
Self::vec_set(
&mut row_arr,
i as i64 + position as i64,
PhpMixed::from(content),
);
}
}
}
}
lengths.push(self.get_cell_width(&row_arr, column));
}
}
self.effective_column_widths.insert(
column,
*lengths.iter().max().unwrap()
+ Helper::width(&self.style.get_cell_row_content_format())
- 2,
);
column += 1;
}
}
fn get_column_separator_width(&self) -> i64 {
Helper::width(&shirabe_php_shim::sprintf(
&self.style.get_border_format(),
&[PhpMixed::from(self.style.get_border_chars()[3].clone())],
))
}
fn get_cell_width(&self, row: &[PhpMixed], column: i64) -> i64 {
let mut cell_width = 0;
if let Some(cell) = Self::row_get_index(row, column) {
cell_width =
Helper::width(&self.remove_decoration(&shirabe_php_shim::to_string(&cell)));
}
let column_width = *self.column_widths.get(&column).unwrap_or(&0);
cell_width = cell_width.max(column_width);
if let Some(max) = self.column_max_widths.get(&column) {
(*max).min(cell_width)
} else {
cell_width
}
}
/// Called after rendering to cleanup cache data.
fn cleanup(&mut self) {
self.effective_column_widths = IndexMap::new();
self.number_of_columns = None;
}
fn init_styles() -> IndexMap<String, TableStyle> {
let mut borderless = TableStyle::default();
borderless
.set_horizontal_border_chars("=".to_string(), None)
.set_vertical_border_chars(" ".to_string(), None)
.set_default_crossing_char(" ".to_string());
let mut compact = TableStyle::default();
compact
.set_horizontal_border_chars("".to_string(), None)
.set_vertical_border_chars("".to_string(), None)
.set_default_crossing_char("".to_string())
.set_cell_row_content_format("%s ".to_string());
let mut style_guide = TableStyle::default();
style_guide
.set_horizontal_border_chars("-".to_string(), None)
.set_vertical_border_chars(" ".to_string(), None)
.set_default_crossing_char(" ".to_string())
.set_cell_header_format("%s".to_string());
let mut r#box = TableStyle::default();
r#box
.set_horizontal_border_chars("─".to_string(), None)
.set_vertical_border_chars("│".to_string(), None)
.set_crossing_chars(
"┼".to_string(),
"┌".to_string(),
"┬".to_string(),
"┐".to_string(),
"┤".to_string(),
"┘".to_string(),
"┴".to_string(),
"└".to_string(),
"├".to_string(),
None,
None,
None,
);
let mut box_double = TableStyle::default();
box_double
.set_horizontal_border_chars("═".to_string(), Some("─".to_string()))
.set_vertical_border_chars("║".to_string(), Some("│".to_string()))
.set_crossing_chars(
"┼".to_string(),
"╔".to_string(),
"╤".to_string(),
"╗".to_string(),
"╢".to_string(),
"╝".to_string(),
"╧".to_string(),
"╚".to_string(),
"╟".to_string(),
Some("╠".to_string()),
Some("╪".to_string()),
Some("╣".to_string()),
);
let mut result: IndexMap<String, TableStyle> = IndexMap::new();
result.insert("default".to_string(), TableStyle::default());
result.insert("borderless".to_string(), borderless);
result.insert("compact".to_string(), compact);
result.insert("symfony-style-guide".to_string(), style_guide);
result.insert("box".to_string(), r#box);
result.insert("box-double".to_string(), box_double);
result
}
fn resolve_style(
&self,
name: PhpMixed,
) -> anyhow::Result<Result<TableStyle, InvalidArgumentException>> {
if shirabe_php_shim::instance_of::<TableStyle>(&name) {
// TODO(phase-b): extract the owned TableStyle out of PhpMixed.
todo!()
}
let name_str = shirabe_php_shim::to_string(&name);
let styles_guard = styles().lock().unwrap();
if let Some(_style) = styles_guard.as_ref().and_then(|s| s.get(&name_str)) {
// TODO(phase-b): TableStyle is not Clone; sharing semantics need resolving.
todo!()
}
Ok(Err(InvalidArgumentException(
shirabe_php_shim::InvalidArgumentException {
message: format!("Style \"{}\" is not defined.", name_str),
code: 0,
},
)))
}
// --- Phase A helpers for `mixed`/array semantics over PhpMixed -------------------------------
//
// These bridge PHP's dynamic typing (a cell is a TableCell, a scalar, null, or an array;
// a row is an array or a TableSeparator) onto PhpMixed. Their bodies are deferred to Phase B
// where the concrete PhpMixed representation is settled.
fn formatter_is_wrappable(_output: &Rc<RefCell<dyn OutputInterface>>) -> bool {
// PHP: $this->output->getFormatter() instanceof WrappableOutputFormatterInterface
// TODO(phase-b): trait-to-trait instanceof check requires concrete formatter knowledge.
let _ = std::any::type_name::<dyn WrappableOutputFormatterInterface>();
todo!()
}
/// PHP `Helper::removeDecoration($this->output->getFormatter(), $string)`.
fn remove_decoration(&self, string: &str) -> String {
let formatter = self.output.borrow().get_formatter();
let mut formatter = formatter.borrow_mut();
Helper::remove_decoration(&mut *formatter, string)
}
fn output_is_console_section(_output: &Rc<RefCell<dyn OutputInterface>>) -> bool {
// PHP: $this->output instanceof ConsoleSectionOutput
todo!()
}
fn is_divider(_row: &PhpMixed, _divider: &TableSeparator) -> bool {
// PHP: $divider === $row (object identity)
todo!()
}
fn cell_colspan(_cell: &PhpMixed) -> i64 {
// PHP: $cell->getColspan()
todo!()
}
fn cell_rowspan(_cell: &PhpMixed) -> i64 {
// PHP: $cell->getRowspan()
todo!()
}
fn cell_get_style(_cell: &PhpMixed) -> Option<TableCellStyle> {
// PHP: $cell->getStyle()
todo!()
}
fn cell_style_is_table_cell_style(_cell: &PhpMixed) -> bool {
// PHP: $cell->getStyle() instanceof TableCellStyle
todo!()
}
fn table_cell_options_colspan(_colspan: i64) -> IndexMap<String, TableCellOption> {
// PHP: ['colspan' => $colspan]
todo!()
}
fn table_cell_options_colspan_style(
_colspan: i64,
_style: Option<TableCellStyle>,
) -> IndexMap<String, TableCellOption> {
// PHP: ['colspan' => $colspan, 'style' => $style]
todo!()
}
fn row_get(_row: &PhpMixed, _index: i64) -> Option<PhpMixed> {
// PHP: isset($row[$i]) ? $row[$i] : null, where $row is an array-typed PhpMixed
todo!()
}
fn row_get_index(_row: &[PhpMixed], _index: i64) -> Option<PhpMixed> {
// PHP: $row[$column] ?? null, honoring sparse integer keys
todo!()
}
fn array_set(_row: &mut [PhpMixed], _index: i64, _value: PhpMixed) {
// PHP: $row[$index] = $value (sparse assignment)
todo!()
}
fn vec_set(_row: &mut Vec<PhpMixed>, _index: i64, _value: PhpMixed) {
// PHP: $row[$index] = $value (sparse assignment)
todo!()
}
/// PHP rows/cells are integer-keyed arrays. We model a row as a positional
/// `Vec<PhpMixed>`. A cell that is a TableCell/TableSeparator cannot be carried by
/// PhpMixed (php-shim limitation), so such conversions are deferred.
fn to_row_vec(_row: PhpMixed) -> Vec<PhpMixed> {
// PHP: an array-typed value seen as a list of cells.
todo!()
}
fn from_row_vec(_row: Vec<PhpMixed>) -> PhpMixed {
// PHP: a list of cells seen as an array-typed value.
todo!()
}
/// PhpMixed cannot hold console value objects (TableCell/TableSeparator). The cell
/// representation is deferred to a later phase.
fn table_cell_to_mixed(_cell: TableCell) -> PhpMixed {
todo!()
}
fn table_separator_to_mixed(_separator: TableSeparator) -> PhpMixed {
todo!()
}
}
|