1
0

Row.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace fphammerle\helpers\table;
  3. use \fphammerle\helpers\StringHelper;
  4. class Row
  5. {
  6. use \fphammerle\helpers\PropertyAccessTrait;
  7. private $_cells = [];
  8. /**
  9. * @param array<mixed> $cell_values
  10. */
  11. public function __construct($cell_values = [])
  12. {
  13. foreach($cell_values as $column_index => $cell_value) {
  14. $this->setCellValue($column_index, $cell_value);
  15. }
  16. }
  17. /**
  18. * @throws InvalidArgumentException
  19. * @param integer $column_index
  20. * @return Cell
  21. */
  22. public function getCell($column_index)
  23. {
  24. if(!is_int($column_index) || $column_index < 0) {
  25. throw new \InvalidArgumentException('column index must be an integer >= 0');
  26. }
  27. if(!isset($this->_cells[$column_index])) {
  28. $this->_cells[$column_index] = new Cell;
  29. }
  30. return $this->_cells[$column_index];
  31. }
  32. /**
  33. * @param integer $column_index
  34. * @param mixed $value
  35. */
  36. public function setCellValue($column_index, $value)
  37. {
  38. $this->getCell($column_index)->value = $value;
  39. }
  40. /**
  41. * @return integer
  42. */
  43. public function getColumnsCount()
  44. {
  45. return sizeof($this->_cells) > 0
  46. ? max(array_keys($this->_cells)) + 1
  47. : 0;
  48. }
  49. /**
  50. * @return string
  51. */
  52. public function toCSV($delimiter = ',', $columns_number = null)
  53. {
  54. if(empty($delimiter)) {
  55. throw new \InvalidArgumentException('empty delimiter');
  56. }
  57. if($columns_number === null) {
  58. $columns_number = $this->columnsCount;
  59. }
  60. $_empty_cell_csv = (new Cell)->toCSV($delimiter);
  61. $_cells_csv = [];
  62. for($column_index = 0; $column_index < $columns_number; $column_index++) {
  63. $_cells_csv[] = isset($this->_cells[$column_index])
  64. ? $this->_cells[$column_index]->toCSV($delimiter)
  65. : $_empty_cell_csv;
  66. }
  67. return implode($delimiter, $_cells_csv) . "\r\n";
  68. }
  69. }