csv_reader.class.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Glossay csv reader class definition
  5. * @package chamilo.glossary
  6. */
  7. /**
  8. * Init
  9. */
  10. namespace Glossary;
  11. /**
  12. * Read a csv file and returns glossary entries 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. $name = isset($item->name) ? trim($item->name) : '';
  53. $description = isset($item->description) ? trim($item->description) : '';
  54. $name = \Security::remove_XSS($name);
  55. $description = \Security::remove_XSS($description);
  56. $is_blank_line = empty($name) && empty($description);
  57. if ($is_blank_line) {
  58. continue;
  59. }
  60. $item = new Glossary();
  61. $item->name = $name;
  62. $item->description = $description;
  63. $result[] = $item;
  64. }
  65. return $result;
  66. }
  67. public function current()
  68. {
  69. $items = $this->get_items();
  70. return isset($items[$this->index]) ? $items[$this->index] : null;
  71. }
  72. public function key()
  73. {
  74. return $this->index;
  75. }
  76. public function next()
  77. {
  78. $this->index++;
  79. }
  80. public function rewind()
  81. {
  82. $this->index = 0;
  83. }
  84. public function valid()
  85. {
  86. $items = $this->get_items();
  87. return count($items) > $this->index;
  88. }
  89. }