csv_reader.class.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Notebook;
  3. /**
  4. * Read a csv file and returns notebook entries 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. $description = isset($item->description) ? trim($item->description) : '';
  46. $name = \Security::remove_XSS($name);
  47. $description = \Security::remove_XSS($description);
  48. $is_blank_line = empty($name) && empty($description);
  49. if ($is_blank_line) {
  50. continue;
  51. }
  52. $item = new Notebook();
  53. $item->title = $title;
  54. $item->description = $description;
  55. $result[] = $item;
  56. }
  57. return $result;
  58. }
  59. public function current()
  60. {
  61. $items = $this->get_items();
  62. return isset($items[$this->index]) ? $items[$this->index] : null;
  63. }
  64. public function key()
  65. {
  66. return $this->index;
  67. }
  68. public function next()
  69. {
  70. $this->index++;
  71. }
  72. public function rewind()
  73. {
  74. $this->index = 0;
  75. }
  76. public function valid()
  77. {
  78. $items = $this->get_items();
  79. return count($items) > $this->index;
  80. }
  81. }