Completed
Push — master ( 4b33bf...219e60 )
by Alies
13s queued 11s
created

Yahoo::generate()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 43
rs 8.6097
c 0
b 0
f 0
cc 6
nc 24
nop 1
1
<?php
2
3
namespace Spatie\CalendarLinks\Generators;
4
5
use DateTimeZone;
6
use Spatie\CalendarLinks\Generator;
7
use Spatie\CalendarLinks\Link;
8
9
/**
10
 * @see https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/yahoo.md
11
 */
12
class Yahoo implements Generator
13
{
14
    /** @var string {@see https://www.php.net/manual/en/function.date.php} */
15
    protected $dateFormat = 'Ymd';
16
    protected $dateTimeFormat = 'Ymd\THis\Z';
17
18
    /** {@inheritdoc} */
19
    public function generate(Link $link): string
20
    {
21
        $url = 'https://calendar.yahoo.com/?v=60&view=d&type=20';
22
23
        $dateTimeFormat = $link->allDay ? $this->dateFormat : $this->dateTimeFormat;
24
25
        if ($link->allDay) {
26
            $url .= '&st='.$link->from->format($dateTimeFormat);
27
            $url .= '&dur=allday';
28
        } else {
29
            $utcStartDateTime = (clone $link->from)->setTimezone(new DateTimeZone('UTC'));
30
            $utcEndDateTime = (clone $link->to)->setTimezone(new DateTimeZone('UTC'));
31
32
            $url .= '&st='.$utcStartDateTime->format($dateTimeFormat);
33
34
            /**
35
             * Yahoo has a bug on parsing end date parameter: it ignores timezone, assuming
36
             * that it's specified in user's tz. In order to bypass it, we can use duration ("dur")
37
             * parameter instead of "et", but this parameter has a limitation cause by it's format HHmm:
38
             * the max duration is 99hours and 59 minutes (dur=9959).
39
             */
40
            $maxDurationInSecs = (59 * 60 * 60) + (59 * 60);
41
            $canUseDuration = $maxDurationInSecs > ($utcEndDateTime->getTimestamp() - $utcStartDateTime->getTimestamp());
42
            if ($canUseDuration) {
43
                $dateDiff = $utcStartDateTime->diff($utcEndDateTime);
44
                $url .= '&dur='.$dateDiff->format('%H%I');
45
            } else {
46
                $url .= '&et='.$utcEndDateTime->format($dateTimeFormat);
47
            }
48
        }
49
50
        $url .= '&title='.urlencode($link->title);
51
52
        if ($link->description) {
53
            $url .= '&desc='.urlencode($link->description);
54
        }
55
56
        if ($link->address) {
57
            $url .= '&in_loc='.urlencode($link->address);
58
        }
59
60
        return $url;
61
    }
62
}
63