csv_writer.class.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace CourseDescription;
  3. use Chamilo;
  4. /**
  5. * Write course descriptions to a file in CSV format.
  6. *
  7. * @license /licence.txt
  8. * @author Laurent Opprecht <laurent@opprecht.info>
  9. */
  10. class CsvWriter
  11. {
  12. /**
  13. *
  14. * @return \CourseDescription\CsvWriter
  15. */
  16. public static function create($path = '')
  17. {
  18. return new self($path);
  19. }
  20. protected $path;
  21. protected $writer;
  22. protected $headers_written = false;
  23. function __construct($path = '')
  24. {
  25. $path = $path ? $path : Chamilo::temp_file();
  26. $this->path = $path;
  27. }
  28. public function get_path()
  29. {
  30. return $this->path;
  31. }
  32. /**
  33. *
  34. * @param array $descriptions
  35. */
  36. public function add_all($descriptions)
  37. {
  38. foreach ($descriptions as $description) {
  39. $this->add($description);
  40. }
  41. }
  42. /**
  43. *
  44. * @param array|CourseDescription $description
  45. */
  46. public function add($description)
  47. {
  48. if (is_array($description)) {
  49. $this->add_all($description);
  50. return;
  51. }
  52. $this->writer_headers();
  53. $data = array();
  54. $data[] = $description->title;
  55. $data[] = $description->content;
  56. $data[] = $description->type->name;
  57. $this->put($data);
  58. }
  59. /**
  60. *
  61. * @return \CsvWriter
  62. */
  63. protected function get_writer()
  64. {
  65. if ($this->writer) {
  66. return $this->writer;
  67. }
  68. $writer = \CsvWriter::create(new \FileWriter($this->path));
  69. $this->writer = $writer;
  70. return $writer;
  71. }
  72. protected function writer_headers()
  73. {
  74. if ($this->headers_written) {
  75. return;
  76. }
  77. $this->headers_written = true;
  78. $headers = array();
  79. $headers[] = 'title';
  80. $headers[] = 'content';
  81. $headers[] = 'type';
  82. $this->put($headers);
  83. }
  84. protected function put($data)
  85. {
  86. $writer = $this->get_writer();
  87. $writer->put($data);
  88. }
  89. }