Table.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace fphammerle\helpers\table;
  3. class Table
  4. {
  5. use \fphammerle\helpers\PropertyAccessTrait;
  6. private $_rows = [];
  7. /**
  8. * @param array<array<mixed>> $cell_values
  9. */
  10. public function __construct($cell_values = [])
  11. {
  12. foreach($cell_values as $row_index => $row_values) {
  13. $this->setRow($row_index, new Row($row_values));
  14. }
  15. }
  16. /**
  17. * @throws InvalidArgumentException
  18. * @param integer $row_index
  19. * @return Row
  20. */
  21. public function getRow($row_index)
  22. {
  23. if(!is_int($row_index) || $row_index < 0) {
  24. throw new \InvalidArgumentException(
  25. sprintf('row index must be an integer >= 0, %s given', print_r($row_index, true))
  26. );
  27. }
  28. if(!isset($this->_rows[$row_index])) {
  29. $this->_rows[$row_index] = new Row;
  30. }
  31. return $this->_rows[$row_index];
  32. }
  33. /**
  34. * @throws InvalidArgumentException
  35. * @param integer $row_index
  36. * @param Row $row
  37. */
  38. public function setRow($row_index, Row $row)
  39. {
  40. if(!is_int($row_index) || $row_index < 0) {
  41. throw new \InvalidArgumentException(
  42. sprintf('row index must be an integer >= 0, %s given', print_r($row_index, true))
  43. );
  44. }
  45. $this->_rows[$row_index] = $row;
  46. }
  47. /**
  48. * @param integer $row_index
  49. * @param integer $column_index
  50. * @return Cell
  51. */
  52. public function getCell($row_index, $column_index)
  53. {
  54. return $this->getRow($row_index)->getCell($column_index);
  55. }
  56. /**
  57. * @param integer $column_index
  58. * @param mixed $value
  59. */
  60. public function setCellValue($row_index, $column_index, $value)
  61. {
  62. $this->getCell($row_index, $column_index)->value = $value;
  63. }
  64. /**
  65. * @return integer
  66. */
  67. public function getColumnsCount()
  68. {
  69. return sizeof($this->_rows) > 0
  70. ? max(array_map(function($r) { return $r->columnsCount; }, $this->_rows))
  71. : 0;
  72. }
  73. /**
  74. * @return string
  75. */
  76. public function toCSV($delimiter = ',')
  77. {
  78. $columns_number = $this->columnsCount;
  79. $empty_row_csv = (new Row)->toCSV($delimiter, $columns_number);
  80. $rows_csv = [];
  81. $rows_number = sizeof($this->_rows) > 0 ? max(array_keys($this->_rows)) + 1 : 0;
  82. for($row_index = 0; $row_index < $rows_number; $row_index++) {
  83. $rows_csv[] = isset($this->_rows[$row_index])
  84. ? $this->_rows[$row_index]->toCSV($delimiter, $columns_number)
  85. : $empty_row_csv;
  86. }
  87. return implode('', $rows_csv);
  88. }
  89. }