csv_reader.class.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Course description's CSV reader class definition
  5. * @package chamilo.course_description
  6. */
  7. /**
  8. * Init
  9. */
  10. namespace CourseDescription;
  11. /**
  12. * Read a csv file and returns course descriptions contained in the file.
  13. *
  14. * @license /licence.txt
  15. * @author Laurent Opprecht <laurent@opprecht.info>
  16. */
  17. class CsvReader implements \Iterator
  18. {
  19. protected $path;
  20. protected $items = null;
  21. protected $index = 0;
  22. public function __construct($path)
  23. {
  24. $this->path = $path;
  25. }
  26. public function get_path()
  27. {
  28. return $this->path;
  29. }
  30. public function get_items()
  31. {
  32. if (is_null($this->items)) {
  33. $this->items = $this->read();
  34. }
  35. return $this->items;
  36. }
  37. /**
  38. * Read file and returns an array filled up with its' content.
  39. *
  40. * @return array of objects
  41. */
  42. protected function read()
  43. {
  44. $result = array();
  45. $path = $this->path;
  46. if (!is_readable($path)) {
  47. return array();
  48. }
  49. $items = \Import::csv_reader($path);
  50. foreach ($items as $item) {
  51. $item = (object) $item;
  52. $title = isset($item->title) ? trim($item->title) : '';
  53. $content = isset($item->content) ? trim($item->content) : '';
  54. $type = isset($item->type) ? trim($item->type) : '';
  55. $title = \Security::remove_XSS($title);
  56. $content = \Security::remove_XSS($content);
  57. $type = \Security::remove_XSS($type);
  58. $is_blank_line = empty($title) && empty($content) && empty($type);
  59. if ($is_blank_line) {
  60. continue;
  61. }
  62. $type = CourseDescriptionType::repository()->find_one_by_name($type);
  63. $type_id = $type ? $type->id : 0;
  64. $description = CourseDescription::create();
  65. $description->title = $title;
  66. $description->content = $content;
  67. $description->description_type = $type_id;
  68. $result[] = $description;
  69. }
  70. return $result;
  71. }
  72. public function current()
  73. {
  74. $items = $this->get_items();
  75. return isset($items[$this->index]) ? $items[$this->index] : null;
  76. }
  77. public function key()
  78. {
  79. return $this->index;
  80. }
  81. public function next()
  82. {
  83. $this->index++;
  84. }
  85. public function rewind()
  86. {
  87. $this->index = 0;
  88. }
  89. public function valid()
  90. {
  91. $items = $this->get_items();
  92. return count($items) > $this->index;
  93. }
  94. }