9 * @author Christian Weiske <cweiske@cweiske.de>
10 * @copyright 2014 Christian Weiske
11 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
12 * @link http://cweiske.de/bdrem.htm
17 * Reads comma separated value files (CSV)
21 * @author Christian Weiske <cweiske@cweiske.de>
22 * @copyright 2014 Christian Weiske
23 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
24 * @link http://cweiske.de/bdrem.htm
29 * Full path of CSV file
35 * If the first line is to be seen as header
38 protected $firstLineIsHeader = true;
41 * If the CSV does not contain a column for the event type,
42 * this text will be used.
45 protected $defaultEvent = 'Birthday';
48 * Field separator in the CSV file
51 protected $separator = ',';
54 * Position of the name, event and date columns. First column is 0.
55 * Use "false" to disable the column (useful for "event").
59 protected $columns = array(
66 * Set the CSV file name
68 * @param array|string $config Config array or path to CSV file
70 public function __construct($config)
72 if (is_string($config)) {
77 $this->filename = $config['filename'];
78 if (!file_exists($this->filename)) {
80 'CSV file does not exist: ' . $this->filename
83 if (isset($config['columns'])) {
84 $this->columns = $config['columns'];
86 if (isset($config['defaultEvent'])) {
87 $this->defaultEvent = $config['defaultEvent'];
89 if (isset($config['separator'])) {
90 $this->separator = $config['separator'];
95 * Return all events for the given date range
97 * @param string $strDate Date the events shall be found for,
99 * @param integer $nDaysPrevious Include number of days before $strDate
100 * @param integer $nDaysNext Include number of days after $strDate
102 * @return Event[] Array of matching event objects
104 public function getEvents($strDate, $nDaysPrevious, $nDaysNext)
106 $handle = fopen($this->filename, 'r');
107 if ($handle === false) {
108 throw new \Exception('Error opening CSV file');
113 while (($row = fgetcsv($handle, 1000, $this->separator)) !== false) {
114 if ($first && $this->firstLineIsHeader) {
119 if ($this->columns['event'] === false) {
120 $eventType = $this->defaultEvent;
122 if (!isset($row[$this->columns['event']])) {
123 throw new \Exception('Event column does not exist in CSV');
125 $eventType = $row[$this->columns['event']];
128 if (!isset($row[$this->columns['date']])) {
129 throw new \Exception('Date column does not exist in CSV');
131 if ($row[$this->columns['date']] == '') {
134 //convert from DD.MM.YYYY to YYYY-MM-DD
138 explode('.', $row[$this->columns['date']])
142 if (!isset($row[$this->columns['name']])) {
143 throw new \Exception('Name column does not exist in CSV');
147 (string) $row[$this->columns['name']],
151 if ($event->isWithin($strDate, $nDaysPrevious, $nDaysNext)) {
152 $arEvents[] = $event;