Cell.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace fphammerle\helpers\table;
  3. use \fphammerle\helpers\StringHelper;
  4. class Cell
  5. {
  6. use \fphammerle\helpers\PropertyAccessTrait;
  7. private $_value = [];
  8. /**
  9. * @param mixed $value
  10. */
  11. public function __construct($value = null)
  12. {
  13. $this->value = $value;
  14. }
  15. /**
  16. * @return mixed
  17. */
  18. public function getValue()
  19. {
  20. return $this->_value;
  21. }
  22. /**
  23. * @param mixed $value
  24. */
  25. public function setValue($value)
  26. {
  27. $this->_value = $value;
  28. }
  29. /**
  30. * @throws InvalidArgumentException
  31. * @return string
  32. */
  33. public function toCSV($delimiter = ',', $quotes = '"')
  34. {
  35. if(empty($delimiter)) {
  36. throw new \InvalidArgumentException('empty delimiter');
  37. } elseif(empty($quotes)) {
  38. throw new \InvalidArgumentException('empty quotes');
  39. } elseif($delimiter == $quotes) {
  40. throw new \InvalidArgumentException('delimiter equals quotes');
  41. }
  42. if($this->value === false) {
  43. return '0';
  44. } else {
  45. $csv = (string)$this->value;
  46. if(StringHelper::containsAny(["\n", "\r", $quotes, $delimiter], $csv)) {
  47. $csv = $quotes . str_replace($quotes, $quotes.$quotes, $csv) . $quotes;
  48. }
  49. return $csv;
  50. }
  51. }
  52. }