Completed
Push — master ( 5600e4...9f95f8 )
by
unknown
01:36 queued 10s
created

Ics::generateEventUid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\CalendarLinks\Generators;
4
5
use Spatie\CalendarLinks\Link;
6
use Spatie\CalendarLinks\Generator;
7
8
/**
9
 * @see https://icalendar.org/RFC-Specifications/iCalendar-RFC-5545/
10
 */
11
class Ics implements Generator
12
{
13
    public function generate(Link $link): string
14
    {
15
        $url = [
16
            'BEGIN:VCALENDAR',
17
            'VERSION:2.0',
18
            'BEGIN:VEVENT',
19
            'UID:'.$this->generateEventUid($link),
20
            'SUMMARY:'.$link->title,
21
        ];
22
23
        if ($link->allDay) {
24
            $dateTimeFormat = 'Ymd';
25
            $url[] = 'DTSTART:'.$link->from->format($dateTimeFormat);
26
            $url[] = 'DTEND:'.$link->to->format($dateTimeFormat);
27
        } else {
28
            $dateTimeFormat = "e:Ymd\THis";
29
            $url[] = 'DTSTART;TZID='.$link->from->format($dateTimeFormat);
30
            $url[] = 'DTEND;TZID='.$link->to->format($dateTimeFormat);
31
        }
32
33
        if ($link->description) {
34
            $url[] = 'DESCRIPTION:'.$this->escapeString($link->description);
35
        }
36
        if ($link->address) {
37
            $url[] = 'LOCATION:'.$this->escapeString($link->address);
38
        }
39
40
        $url[] = 'END:VEVENT';
41
        $url[] = 'END:VCALENDAR';
42
        $redirectLink = implode('%0d%0a', $url);
43
44
        return 'data:text/calendar;charset=utf8,'.$redirectLink;
45
    }
46
47
    /** @see https://tools.ietf.org/html/rfc5545.html#section-3.3.11 */
48
    protected function escapeString(string $field): string
49
    {
50
        return addcslashes($field, "\n,;");
51
    }
52
53
    /** @see https://tools.ietf.org/html/rfc5545#section-3.8.4.7 */
54
    protected function generateEventUid(Link $link): string
55
    {
56
        return md5($link->from->format(\DateTime::ATOM).$link->to->format(\DateTime::ATOM).$link->title.$link->address);
57
    }
58
}
59