A comprehensive Symfony bundle for integrating multiple calendar providers (Google Calendar, Microsoft Calendar) into your Symfony application. Provides a unified interface for OAuth authentication, event management, webhook notifications, and event synchronization.
- Google Calendar ✅ - Full OAuth2 flow, event CRUD, webhooks (7-day expiration), and incremental sync
- Microsoft Calendar ✅ - Full OAuth2 flow, event CRUD, webhooks (3-day expiration), and delta queries
- Simplified OAuth2 flow with automatic token management
- Automatic token refresh when expired
- Clean disconnect with optional event cleanup
- Secure token storage with Doctrine ORM
- Create, read, update, and delete calendar events
- Support for all-day events, recurring events, and attendees
- Timezone handling
- Batch operations for performance
- Webhook push notifications from calendar providers
- Incremental sync with sync tokens (no polling required)
- Event-driven architecture for processing changes
- Console commands for scheduled synchronization
- Clean, well-documented API
- Comprehensive test coverage (359 tests, 805 assertions)
- Event system for extensibility
- PSR-3 logging support
- Symfony best practices
- Minimal configuration required
- PHP 8.1 or higher
- Symfony 6.4 or higher
- Doctrine ORM
- Google API Client Library (
google/apiclient ^2.15) - Microsoft Graph SDK (
microsoft/microsoft-graph ^2.54)
composer require digital-ascetic/calendar-gateway-bundleIf you're using Symfony Flex, the bundle is enabled automatically. Otherwise, add it to config/bundles.php:
return [
// ...
DigitalAscetic\CalendarGatewayBundle\DigitalAsceticCalendarGatewayBundle::class => ['all' => true],
];Copy the example configuration:
cp vendor/digital-ascetic/calendar-gateway-bundle/config/calendar_gateway.yaml.dist config/packages/digital_ascetic_calendar_gateway.yamlEdit config/packages/digital_ascetic_calendar_gateway.yaml:
digital_ascetic_calendar_gateway:
enabled: true
# Event entity class (REQUIRED)
event_class: App\Entity\Event # Must implement ICalendarEvent
# User entity configuration
user:
user_class: App\Entity\User # Must implement ICalendarUser
property_id: id
# Protocol for webhook URLs
protocol: https
# Global webhook configuration
webhooks:
enabled: true
auto_enable: true # Auto-enable webhooks when user connects
# Calendar providers
providers:
# Google Calendar
google:
enabled: true
client_secret_file: '%kernel.project_dir%/config/google_client_secret.json'
application_name: 'My Application'
redirect_uri: null # Optional: auto-detected if not provided
clean_disconnect: true
webhooks:
enabled: true
# Microsoft Calendar
microsoft:
enabled: true
tenant_id: 'common' # or your specific tenant ID
client_id: '%env(MICROSOFT_CLIENT_ID)%'
client_secret: '%env(MICROSOFT_CLIENT_SECRET)%'
redirect_uri: null # Optional: auto-detected if not provided
clean_disconnect: true
webhooks:
enabled: trueYour User entity must implement ICalendarUser:
namespace App\Entity;
use DigitalAscetic\CalendarGatewayBundle\Entity\ICalendarUser;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
class User implements ICalendarUser
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
public function getId(): ?int
{
return $this->id;
}
}Your Event entity must implement ICalendarEvent. This interface ensures your events can be synchronized with calendar providers:
namespace App\Entity;
use DigitalAscetic\CalendarGatewayBundle\Entity\CalendarConnection;
use DigitalAscetic\CalendarGatewayBundle\Entity\ICalendarEvent;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
class Event implements ICalendarEvent
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(type: 'json', nullable: true)]
private ?array $providerEventIds = [];
#[ORM\ManyToOne(targetEntity: CalendarConnection::class)]
private ?CalendarConnection $calendarConnection = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
#[ORM\Column(type: 'datetime')]
private ?\DateTimeInterface $startDateTime = null;
#[ORM\Column(type: 'datetime')]
private ?\DateTimeInterface $endDateTime = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string $description = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $location = null;
#[ORM\Column(type: 'boolean')]
private bool $allDay = false;
// Implement ICalendarEvent interface methods
public function getProviderEventId(): ?string
{
if ($this->calendarConnection === null) {
return null;
}
$provider = $this->calendarConnection->getProvider();
return $this->providerEventIds[$provider->value] ?? null;
}
public function setProviderEventId(?string $eventId): self
{
if ($this->calendarConnection === null) {
throw new \LogicException('Cannot set provider event ID without a calendar connection');
}
$provider = $this->calendarConnection->getProvider();
if ($eventId === null) {
unset($this->providerEventIds[$provider->value]);
} else {
$this->providerEventIds[$provider->value] = $eventId;
}
return $this;
}
// ... other getters and setters
}The bundle handles all event queries internally using CalendarEventRepository - you don't need to implement any custom event service.
php bin/console doctrine:schema:update --forceOr use migrations (recommended):
php bin/console make:migration
php bin/console doctrine:migrations:migrate- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable the Google Calendar API
- Create OAuth 2.0 credentials (Web application)
- Add authorized redirect URI:
https://yourdomain.com/calendar/auth/google/authorize/user/{userId} - Download the credentials JSON file
- Save it as
config/google_client_secret.json
- Go to Azure Portal
- Navigate to Azure Active Directory → App registrations
- Click "New registration"
- Set name and supported account types (e.g., "Accounts in any organizational directory and personal Microsoft accounts")
- Add redirect URI:
https://yourdomain.com/calendar/auth/microsoft/authorize/user/{userId} - After creation, copy the Application (client) ID
- Go to "Certificates & secrets" → "New client secret"
- Copy the client secret value
- Go to "API permissions" → "Add permission" → "Microsoft Graph" → "Delegated permissions"
- Add these permissions:
Calendars.ReadWriteoffline_access
- Add credentials to your
.envfile:MICROSOFT_CLIENT_ID=your-client-id MICROSOFT_CLIENT_SECRET=your-client-secret
use DigitalAscetic\CalendarGatewayBundle\Enum\CalendarProvider;
use DigitalAscetic\CalendarGatewayBundle\Service\CalendarGatewayService;
class CalendarController extends AbstractController
{
public function __construct(
private readonly CalendarGatewayService $calendarGateway
) {}
#[Route('/calendar/connect', name: 'calendar_connect')]
public function connect(): Response
{
$user = $this->getUser();
// Get authorization URL
$authUrl = $this->calendarGateway->getAuthorizationUrl(
$user,
CalendarProvider::GOOGLE
);
return $this->redirect($authUrl);
}
}The bundle provides a built-in callback endpoint at:
/calendar/auth/{provider}/authorize/user/{userId}
The callback automatically:
- Exchanges authorization code for access token
- Creates a
CalendarConnectionentity - Dispatches
CalendarConnectionEvent::CONNECTED - Auto-enables webhooks (if configured)
- Returns JSON response with connection details
You can also handle the callback manually:
#[Route('/calendar/callback', name: 'calendar_callback')]
public function callback(Request $request): Response
{
$code = $request->query->get('code');
$user = $this->getUser();
try {
$connection = $this->calendarGateway->createConnection(
$user,
CalendarProvider::GOOGLE,
$code
);
$this->addFlash('success', 'Calendar connected successfully!');
return $this->redirectToRoute('dashboard');
} catch (\Exception $e) {
$this->addFlash('error', 'Failed to connect: ' . $e->getMessage());
return $this->redirectToRoute('settings');
}
}// Get user's calendar connection
$connections = $this->calendarGateway->getUserConnections($user);
$connection = $connections[0];
// List upcoming events
$events = $this->calendarGateway->listEvents($connection, [
'timeMin' => new \DateTime('now'),
'timeMax' => (new \DateTime('now'))->modify('+1 week'),
'maxResults' => 50,
'orderBy' => 'startTime',
]);
foreach ($events as $event) {
echo sprintf(
"%s - %s\n",
$event->getTitle(),
$event->getStartDateTime()->format('Y-m-d H:i')
);
}use App\Entity\CalendarEvent;
// Assuming your CalendarEvent entity implements ICalendarEvent
$event = new CalendarEvent();
$event->setTitle('Team Meeting')
->setDescription('Quarterly planning meeting')
->setLocation('Conference Room A')
->setStartDateTime(new \DateTime('2024-12-20 10:00:00'))
->setEndDateTime(new \DateTime('2024-12-20 11:00:00'))
->setTimezone('America/New_York')
->addAttendee('john@example.com')
->addAttendee('jane@example.com');
// Create event in Google Calendar
$eventDTO = $this->calendarGateway->createEvent($connection, $event);
// The provider event ID is automatically stored in your entity
echo "Event created with ID: " . $event->getProviderEventId($connection->getProvider());$providerEventId = $event->getProviderEventId(CalendarProvider::GOOGLE);
// Update the event
$event->setTitle('Updated Team Meeting');
$eventDTO = $this->calendarGateway->updateEvent($connection, $providerEventId, $event);$providerEventId = $event->getProviderEventId(CalendarProvider::GOOGLE);
$this->calendarGateway->deleteEvent($connection, $providerEventId);The bundle provides built-in webhook endpoints:
- Google Calendar:
POST /calendar/webhook/google - Microsoft Calendar:
GET|POST /calendar/webhook/microsoft
Webhooks are automatically enabled when a user connects if webhooks.auto_enable: true is configured.
To manually enable webhooks:
$channel = $this->calendarGateway->enableWebhooks($connection);
echo "Webhook enabled: " . $channel->getChannelId();
echo "Expires at: " . $channel->getExpiresAt()->format('Y-m-d H:i:s');// Disable all webhooks for a connection
$this->calendarGateway->disableWebhooks($connection);
// Or disable a specific channel
$this->calendarGateway->disableWebhooks($channel);// Renew a webhook channel before it expires
$newChannel = $this->calendarGateway->renewWebhook($channel);When a webhook notification is received:
CalendarWebhookControllervalidates and processes the notificationCalendarWebhookEventis dispatchedCalendarWebhookListenerupdates notification counters- If changes detected,
CalendarSyncEvent::SYNC_STARTEDis dispatched syncEvents()is called to fetch changes from the providerCalendarEventRepositoryupdates your Event entities with the changesCalendarSyncEvent::SYNC_COMPLETEDis dispatched
$result = $this->calendarGateway->syncEvents($connection);
echo "Sync completed:\n";
echo "- Total processed: {$result->getTotalProcessed()}\n";
echo "- Created: {$result->getCreatedCount()}\n";
echo "- Updated: {$result->getUpdatedCount()}\n";
echo "- Deleted: {$result->getDeletedCount()}\n";
echo "- Errors: {$result->getErrorCount()}\n";
if ($result->hasErrors()) {
foreach ($result->getErrors() as $error) {
echo "Error: {$error['message']}\n";
}
}Synchronizes events for channels that have received webhook notifications:
# Sync all channels with pending notifications
php bin/console calendar:sync
# Sync only Google Calendar channels
php bin/console calendar:sync --provider=google
# Sync channels notified after a specific date
php bin/console calendar:sync --from=2024-01-01
# Force sync all active channels (ignore notification status)
php bin/console calendar:sync --force
# Verbose output
php bin/console calendar:sync -vRenews webhook channels before they expire:
# Renew channels expiring in next 24 hours (default)
php bin/console calendar:webhook:renew
# Renew channels expiring in next 48 hours
php bin/console calendar:webhook:renew --hours=48
# Also clean up expired channels
php bin/console calendar:webhook:renew --clean
# Filter by provider
php bin/console calendar:webhook:renew --provider=googleAdd these to your crontab for automated synchronization:
# Sync events every 5 minutes
*/5 * * * * cd /path/to/project && php bin/console calendar:sync >> /var/log/calendar-sync.log 2>&1
# Renew webhooks every 6 hours and clean up expired ones
0 */6 * * * cd /path/to/project && php bin/console calendar:webhook:renew --clean >> /var/log/calendar-webhooks.log 2>&1The bundle dispatches events that you can listen to for custom logic:
use DigitalAscetic\CalendarGatewayBundle\Event\CalendarConnectionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CalendarConnectionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CalendarConnectionEvent::NAME_CONNECTED => 'onConnectionConnected',
CalendarConnectionEvent::NAME_DISCONNECTED => 'onConnectionDisconnected',
CalendarConnectionEvent::NAME_TOKEN_REFRESHED => 'onTokenRefreshed',
];
}
public function onConnectionConnected(CalendarConnectionEvent $event): void
{
$connection = $event->getConnection();
$provider = $event->getProvider();
// Send welcome email, log activity, etc.
$this->logger->info('User connected calendar', [
'user_id' => $connection->getUserId(),
'provider' => $provider->value,
]);
}
public function onConnectionDisconnected(CalendarConnectionEvent $event): void
{
// Clean up related data, notify user, etc.
}
public function onTokenRefreshed(CalendarConnectionEvent $event): void
{
// Log token refresh for monitoring
}
}use DigitalAscetic\CalendarGatewayBundle\Event\CalendarWebhookEvent;
class CalendarWebhookSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CalendarWebhookEvent::NAME => 'onWebhookReceived',
];
}
public function onWebhookReceived(CalendarWebhookEvent $event): void
{
$payload = $event->getPayload();
$channel = $event->getChannel();
// Log webhook activity
$this->logger->info('Webhook received', [
'provider' => $payload->getProvider()->value,
'channel_id' => $channel->getChannelId(),
'change_type' => $payload->getChangeType(),
'requires_sync' => $event->requiresSync(),
]);
if ($event->requiresSync()) {
// Send notification, trigger background job, etc.
}
}
}use DigitalAscetic\CalendarGatewayBundle\Event\CalendarSyncEvent;
class CalendarSyncSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CalendarSyncEvent::NAME_SYNC_STARTED => 'onSyncStarted',
CalendarSyncEvent::NAME_SYNC_COMPLETED => 'onSyncCompleted',
CalendarSyncEvent::NAME_SYNC_FAILED => 'onSyncFailed',
];
}
public function onSyncStarted(CalendarSyncEvent $event): void
{
// Mark sync as in progress in UI, send notification, etc.
}
public function onSyncCompleted(CalendarSyncEvent $event): void
{
$result = $event->getResult();
// Log results
$this->logger->info('Sync completed', [
'created' => $result->getCreatedCount(),
'updated' => $result->getUpdatedCount(),
'deleted' => $result->getDeletedCount(),
]);
// Send notification to user
$this->notifier->notify(
$event->getConnection()->getUser(),
"Calendar synced: {$result->getSummary()}"
);
}
public function onSyncFailed(CalendarSyncEvent $event): void
{
$error = $event->getError();
// Log error, send alert, retry logic, etc.
$this->logger->error('Sync failed', [
'error' => $error->getMessage(),
'connection_id' => $event->getConnection()->getId(),
]);
}
}The bundle includes comprehensive test coverage:
# Run all tests
vendor/bin/phpunit
# Run with testdox format (readable output)
vendor/bin/phpunit --testdox
# Run specific test class
vendor/bin/phpunit tests/Service/CalendarGatewayServiceTest.php
# Run tests with coverage
vendor/bin/phpunit --coverage-html coverage- 328 tests across all components
- 758 assertions covering critical functionality
- 100% pass rate ✅
- ✅ Entities and DTOs
- ✅ Google Calendar API services
- ✅ Provider implementations
- ✅ Core services (Gateway, Factory)
- ✅ Controllers (Auth, Webhooks)
- ✅ Event system
- ✅ Console commands
- ✅ Repositories
The bundle uses an abstract provider pattern for easy extension:
CalendarProviderInterface
↑
AbstractCalendarProvider (shared logic, batch processing, logging)
↑
├── GoogleCalendarProvider (implemented ✅)
│ ├── GoogleApiClient
│ ├── GoogleAuthService
│ ├── GoogleCalendarApiService
│ └── GoogleWebhookService
│
└── MicrosoftCalendarProvider (architecture ready 🔜)
├── MicrosoftGraphClient
├── MicrosoftAuthService
├── MicrosoftCalendarApiService
└── MicrosoftWebhookService
- CalendarGatewayService: Main facade for all calendar operations
- CalendarProviderFactory: Creates provider instances using Symfony tagged iterator
- Provider-specific services: Encapsulate provider logic (Google, Microsoft)
- CalendarConnection: OAuth tokens, connection metadata
- CalendarWebhookChannel: Webhook subscriptions and sync state
- ICalendarUser: Interface for your User entity
- ICalendarEvent: Interface for your Event entity
- Lifecycle events for connections (connect, disconnect, token refresh)
- Webhook events for real-time notifications
- Sync events for synchronization tracking
- Extensible through Symfony EventDispatcher
digital_ascetic_calendar_gateway:
# Enable/disable the entire bundle
enabled: true
# Event entity class (REQUIRED)
event_class: App\Entity\Event # Entity implementing ICalendarEvent
# User entity configuration
user:
user_class: App\Entity\User # Entity implementing ICalendarUser
property_id: id # Primary key property name
# Protocol for webhook URLs (http or https)
protocol: https
# Global webhook configuration
webhooks:
enabled: true # Enable webhook functionality
auto_enable: true # Auto-enable webhooks on new connections
# Calendar providers
providers:
# Google Calendar
google:
enabled: true
client_secret_file: '%kernel.project_dir%/config/google_client_secret.json'
application_name: 'My Application'
redirect_uri: null # Optional: auto-detected
clean_disconnect: true # Delete events on disconnect
webhooks:
enabled: true # Enable webhooks for this provider
# Microsoft Calendar (not yet implemented)
microsoft:
enabled: false
tenant_id: 'common'
client_id: '%env(MICROSOFT_CLIENT_ID)%'
client_secret: '%env(MICROSOFT_CLIENT_SECRET)%'
redirect_uri: null
clean_disconnect: true
webhooks:
enabled: trueProblem: redirect_uri_mismatch error during authentication
Solution: Ensure your redirect URI in Google Cloud Console matches exactly:
https://yourdomain.com/calendar/auth/google/authorize/user/{userId}
Note: {userId} is a literal placeholder in the Google Console, it will be replaced at runtime.
Problem: invalid_grant error
Solution: The authorization code has expired or already been used. Restart the OAuth flow.
Problem: invalid_grant error when refreshing token
Solution: The refresh token may have been revoked. User needs to disconnect and reconnect their calendar.
Problem: Webhook notifications not being received
Solutions:
- Ensure webhook URL is publicly accessible via HTTPS
- Check
webhooks.enabled: truein configuration - Verify webhook channel is active:
SELECT * FROM calendar_webhook_channel WHERE is_active = 1 - Check application logs for validation errors
- Test webhook endpoint manually:
curl -X POST https://yourdomain.com/calendar/webhook/google -H "X-Goog-Channel-ID: test"
Problem: Webhooks expire too quickly
Solution: Set up the renewal cron job:
0 */6 * * * php bin/console calendar:webhook:renew --cleanProblem: Events not syncing despite webhooks working
Solutions:
- Check that your Event entity implements
ICalendarEventinterface correctly - Verify sync tokens are being stored: Check
sync_tokenfield incalendar_webhook_channeltable - Run manual sync with verbose output:
php bin/console calendar:sync -vvv - Check application logs for errors during sync
- Force full sync:
php bin/console calendar:sync --force
Problem: Duplicate events after sync
Solution: The bundle's CalendarEventRepository automatically handles duplicate detection using providerEventId. If you're still seeing duplicates, ensure your Event entity correctly implements the getProviderEventId() and setProviderEventId() methods from ICalendarEvent interface.
Problem: Foreign key constraint errors
Solution: Ensure migrations are run in correct order. The bundle entities should be created before adding relationships.
Problem: Slow event synchronization
Solutions:
- Ensure sync tokens are being used (check logs for "incremental sync" vs "full sync")
- Enable incremental sync in your implementation
- Use batch processing for large event sets
- Consider running sync in background jobs instead of synchronously
Migrating from another calendar bundle? See MIGRATION_GUIDE.md for detailed instructions on:
- Migrating from
digitalascetic/google-api-clientbundle - Database schema migration
- Configuration migration
- Code examples (before/after)
- Common pitfalls
See CHANGELOG.md for version history and release notes.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Add tests for new functionality
- Ensure all tests pass (
vendor/bin/phpunit) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
# Clone the repository
git clone https://github.com/digital-ascetic/calendar-gateway-bundle.git
cd calendar-gateway-bundle
# Install dependencies
composer install
# Run tests
vendor/bin/phpunit
# Run code style checks
vendor/bin/php-cs-fixer fix --dry-runThis bundle is released under the MIT License. See LICENSE file for details.
- Issues: https://github.com/digital-ascetic/calendar-gateway-bundle/issues
- Discussions: https://github.com/digital-ascetic/calendar-gateway-bundle/discussions
- Email: support@ascetic.io
- Google Calendar integration
- OAuth2 authentication and token management
- Event CRUD operations
- Webhook notifications
- Incremental synchronization
- Console commands
- Comprehensive test coverage
- Microsoft Calendar integration
- Calendar event search
- Recurring event support enhancements
- Calendar sharing/permissions management
- Meeting room booking integration
Developed and maintained by Digital Ascetic
- Built with Symfony
- Google Calendar integration via Google API PHP Client
- Inspired by the Symfony community's best practices
Status: Production Ready | Version: 1.0.0 | Last Update: 2026-01-09