This repository has been archived by the owner on Jan 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.php
112 lines (90 loc) · 2.76 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace ical;
use ical\Calendar;
use ical\Event;
class Parser
{
const WHITESPACE = " ";
protected $calendar;
/**
* Reads an .ics file and returns a ical\Calendar-object
* @param string $filename
* @return ical\Calender
*/
public function readfile($filename) {
mb_internal_encoding("UTF-8");
$chunks = $this->parseChunks($this->unfolddata(file(realpath($filename))));
$calendar = $this->processChunks($chunks);
return $calendar;
}
protected function processChunks($chunks) {
$calendar = new \ical\Calendar;
// Find the CALENDAR chunk
foreach ($chunks as $chunk) {
if (\ical\parser\Chunk::TYPE_CALENDAR === $chunk->type) {
$calendar = \ical\Calendar::createFromChunk($chunk);
break;
}
}
foreach ($chunks as $chunk) {
switch ($chunk->type) {
case \ical\parser\Chunk::TYPE_TIMEZONE:
break;
case \ical\parser\Chunk::TYPE_TZ_DST:
break;
case \ical\parser\Chunk::TYPE_TZ_STD:
break;
case \ical\parser\Chunk::TYPE_EVENT:
$event = \ical\Event::createFromChunk($chunk);
$calendar->addEvent($event);
break;
}
}
return $calendar;
}
/**
* Parse a .ics-file into chunks
* @param array $data
* @return array
*/
protected function parseChunks($data) {
$chunks = array();
$stack = array();
$cursor = -1;
foreach ($data as $rownum => $raw) {
$row = new \ical\parser\Row($raw, $rownum);
switch ($row->name) {
case "BEGIN":
array_unshift($stack, new \ical\parser\Chunk($row));
break;
case "END";
array_unshift($chunks, array_shift($stack));
break;
default:
$stack[0]->addRow($row);
break;
}
}
if (count($stack) > 0) {
throw new \Exception("Calendar data not well formed.");
}
return $chunks;
}
/**
* Unfolds data that has been split onto several rows
* @param array $folded
* @return array
*/
protected function unfolddata($folded) {
$cursor = -1;
$ret = array();
foreach ($folded as $row) {
if (mb_substr($row, 0, 1) === self::WHITESPACE) {
$ret[$cursor] .= rtrim(mb_substr($row, 1), "\r\n");
} else {
$ret[++$cursor] = rtrim($row, "\r\n");
}
}
return $ret;
}
}