csv_writer.class.php 2.1 KB

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