This repository has been archived on 2020-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
ical-drupal-calendar/includes/ICSFileReader.php

90 lines
3.0 KiB
PHP

<?php
namespace Pandy06269\iCalDrupal\includes;
class ICSFileReader extends FileReader implements IEventReader
{
const HEADER_VCALENDAR_BEGIN = 'BEGIN:VCALENDAR';
const HEADER_VCALENDAR_END = 'END:VCALENDAR';
const HEADER_VEVENT_BEGIN = 'BEGIN:VEVENT';
const HEADER_VEVENT_END = 'END:VEVENT';
const HEADER_DATE = 'DTSTART:';
const HEADER_DATE_END = 'DTEND:';
const HEADER_DESCRIPTION = 'DESCRIPTION:';
const HEADER_TITLE = 'SUMMARY:';
const HEADER_UID = 'UID:';
/**
* @var Event
*/
private $currentEvent = null;
/**
* @var bool
*/
private $isDescriptionStarted = false;
public function getEvents()
{
$events = [];
$lineCount = 0;
while (($line = $this->read()) !== false)
{
if (defined('DEBUG'))
{
echo sprintf('L%d: %s', $lineCount + 1, $line) . PHP_EOL;
}
// First line should be BEGIN:VCALENDAR
if ($lineCount === 0 && trim($line) !== self::HEADER_VCALENDAR_BEGIN)
{
throw new \Exception('The file does not appear to be a valid iCal file');
}
if ($lineCount > 0)
{
if ($line == self::HEADER_VEVENT_BEGIN)
{
$this->currentEvent = new Event();
}
else if ($line == self::HEADER_VEVENT_END)
{
$events[] = $this->currentEvent;
}
else if (!is_null($this->currentEvent))
{
if (substr($line, 0, strlen(self::HEADER_UID)) == self::HEADER_UID)
{
$this->currentEvent->setUid(trim(substr($line, strlen(self::HEADER_UID))));
}
else if (substr($line, 0, strlen(self::HEADER_TITLE)) == self::HEADER_TITLE)
{
$this->currentEvent->setTitle(trim(substr($line, strlen(self::HEADER_TITLE))));
}
else if (substr($line, 0, strlen(self::HEADER_DATE)) == self::HEADER_DATE)
{
$date = \DateTime::createFromFormat('Ymd\\THis\\Z', trim(substr($line, strlen(self::HEADER_DATE))));
$this->currentEvent->setStartDate($date);
}
else if (substr($line, 0, strlen(self::HEADER_DESCRIPTION)) == self::HEADER_DESCRIPTION)
{
$this->isDescriptionStarted = true;
$description = trim(substr($line, strlen(self::HEADER_DESCRIPTION)));
while (preg_match('/^\s/', $line = $this->read()))
{
$description .= ' ' . trim($line);
}
$this->currentEvent->setDescription($description);
}
}
}
$lineCount++;
}
return $events;
}
}