csv_reader.class.php 2.4 KB

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