spatie/icalendar-generator

repository·main·Indexed 20 days ago

https://github.com/spatie/icalendar-generator

A PHP package for generating calendars in the iCalendar format (RFC 5545) and supporting extensions from RFC 7986. It provides a fluent API to create calendars, events, and todo items that can be imported into applications like Google Calendar or Apple Calendar. Features include support for RRules for repeating events, timezone management, and the ability to extend the package with custom properties or components.

Tokens
7.3K
Snippets
30
Records
33
Agent score
71%

What's inside spatie/icalendar-generator

  1. Handle Timezones in calendars and events

    main

    By default, the package uses the timezone defined in the DateTime objects provided. If no timezone is provided, it defaults to UTC.

    Key Concepts:

    • Disabling Timezones: Use withoutTimezone() on an Event or a Calendar to treat times as floating/local time.
    • Auto-Timezone Components: The package automatically adds Timezone components to the iCalendar output. Disable this with withoutAutoTimezoneComponents() on the Calendar.
    • Manual Timezone Crafting: You can manually define Timezone and TimezoneEntry objects to describe daylight savings transitions or specific offsets.
    // Event without a timezone (floating time)
    Event::create()
        ->startsAt(new DateTime('2019-03-06 12:00'))
        ->withoutTimezone();
    
    // Calendar without automatic timezone components
    Calendar::create()->withoutAutoTimezoneComponents();
  2. Upgrade from 1.x to 2.x: Breaking changes

    main

    When upgrading from version 1.x to 2.x, be aware of the following breaking changes:

    • PHP Version: Requires PHP 7.4 or 8.0.
    • Timezones: Timezones are now opt-out instead of opt-in, meaning every date property will now include a timezone.
    • Properties: Property types are now referred to simply as properties.
    • Property Names: Properties now only accept a string as a name. To use alternative names, you must use the addAlias() function.
    • ComponentPayload: The methods textProperty, dateTimeProperty, and when have been removed. They are replaced by property, optional, and multiple.
  3. Create a basic calendar

    main

    Use Calendar::create() to initialize a new calendar. You can optionally provide a name and a description. To generate the final iCalendar text format for streaming or downloading, call the get() method.

    $calendar = Calendar::create('Laracon Online')
        ->description('Experience Laracon all around the world');
    
    echo $calendar->get(); // BEGIN:VCALENDAR ...
  4. Stream calendars in Laravel

    main

    To serve a calendar as a response in a Laravel application, set the Content-Type to text/calendar; charset=utf-8. To force a download, include a Content-Disposition header.

    // Stream to calendar app
    return response($calendar->get())
        ->header('Content-Type', 'text/calendar; charset=utf-8');
    
    // Force download as .ics file
    return response($calendar->get(), 200, [
       'Content-Type' => 'text/calendar; charset=utf-8',
       'Content-Disposition' => 'attachment; filename="my-calendar.ics"',
    ]);
  5. Upgrade from 2.x to 3.x: Use native PHP enums

    main

    In version 3.x, the dependency on spatie/enum was removed in favor of native PHP enums. If you use any of the package's enums in your own code, you must update your calls from method-based access to constant-based access.

    The affected enums are:

    • Spatie\IcalendarGenerator\Enums\Classification
    • Spatie\IcalendarGenerator\Enums\Display
    • Spatie\IcalendarGenerator\Enums\EventStatus
    • Spatie\IcalendarGenerator\Enums\ParticipationStatus
    • Spatie\IcalendarGenerator\Enums\RecurrenceDay
    • Spatie\IcalendarGenerator\Enums\RecurrenceFrequency
    • Spatie\IcalendarGenerator\Enums\RecurrenceMonth
    • Spatie\IcalendarGenerator\Enums\TimezoneEntryType
    // Old way (2.x)
    RecurrenceMonth::january();
    
    // New way (3.x)
    RecurrenceMonth::January;
  6. Generate an iCalendar string

    main

    You can generate an iCalendar (RFC 5545) compliant string by using the Calendar and Event components. The Calendar::create() method initializes a new calendar with a name, and you can chain event() calls to add events created via Event::create().

    use Spatie\IcalendarGenerator\Components\Calendar;
    use Spatie\IcalendarGenerator\Components\Event;
    
    Calendar::create('Laracon online')
        ->event(Event::create('Creating calender feeds')
            ->startsAt(new DateTime('6 March 2019 15:00'))
            ->endsAt(new DateTime('6 March 2019 16:00'))
        )
        ->get();
  7. Create Todo items

    main

    Todos are tasks that can be added to a calendar. They differ from events in that they focus on completion and due dates.

    Key Todo Methods:

    • starts(DateTime $date): When the todo starts.
    • due(DateTime $date): The deadline (cannot be used with starts()).
    • duration(DateInterval $interval): How long the todo lasts (requires starts()).
    • completedAt(DateTime $date): When the todo was finished.
    • percentComplete(int $percent): Progress from 0 to 100.
    • priority(int $priority): Priority from 1 to 9.
    • status(TodoStatus $status): Status (e.g., Completed, InProcess, NeedsAction, Cancelled).
    $todo = Todo::create('My first todo')
        ->due(new DateTime('2023-12-31 23:59:59'))
        ->priority(5)
        ->status(TodoStatus::InProcess);
    
    Calendar::create('My Tasks')->todo($todo);
  8. Add events to a calendar

    main

    Once an event is created, it must be added to a Calendar instance. You can add events in three ways:

    1. Single Event: Pass an Event object directly.
    2. Array of Events: Pass an array of Event objects.
    3. Closure: Pass a closure that receives an Event instance for inline configuration.
    // Single event
    Calendar::create('Laracon Online')->event(Event::create('Event Name'));
    
    // Array of events
    Calendar::create('Laracon Online')->event([
        Event::create('Event 1'),
        Event::create('Event 2'),
    ]);
    
    // Closure
    Calendar::create('Laracon Online')->event(function(Event $event) {
        $event->name('Creating calendar feeds');
    });
  9. Create repeating events with RRules

    main

    To create complex repeating patterns, use RRule. You can define frequency, intervals, and specific constraints like weekdays or months.

    Recurrence Frequencies: Daily, Weekly, Monthly, Yearly, Hourly, Minutely, Secondly.

    Common RRule Methods:

    • starting(DateTime $date): When the rule starts.
    • until(DateTime $date): When the rule stops.
    • times(int $count): Repeat a specific number of times.
    • interval(int $interval): The gap between repetitions.
    • onWeekDay(RecurrenceDay $day, int $occurrence = 1): Repeat on a specific weekday (e.g., the 3rd Friday).
    • onMonthDay(int|array $days): Repeat on specific days of the month.
    • onMonth(array $months): Repeat only during specific months.
    • doNotRepeatOn(DateTime|array $dates): Exclude specific dates from the recurrence.
    // Example: Monthly on the last Friday
    $rrule = RRule::frequency(RecurrenceFrequency::Monthly)
        ->onWeekDay(RecurrenceDay::Friday, -1);
    
    Event::create('Monthly Meeting')->rrule($rrule);
    
    // Example: Daily with an interval of 2
    Event::create('Every other day')->rrule(RRule::frequency(RecurrenceFrequency::Daily)->interval(2));