How to work with Google API / Calendar / freebusy response in Yii2

Today I had an issue with Google API Calendar service, specifically freebusy method.

Since I did a API in yii2 to check availability for some calendars my response from calendar->freebusy->query() it was look that returns empty :o so I started to deal with this issue until I found a solution. The solution was, after run query() method there is another method called toSimpleObject() is a helper to transform from a Google Resource Object to a PHP Array Object.

This is a piece of code for sample this issue.

public function actionFreebusy() {
  $request = Yii::$app->request;
  $response = [
    "valid" => true,
    "message" => false,
    "data" => []
  ];
  Yii::$app->response->format = 'json';

  $service = Yii::$app->calendar->getService();
  $freebusyItems = [];

  $data = $request->post();

  $freebusy = new \Google_Service_Calendar_FreeBusyRequest();

  $timeMin = new \DateTime($data['timeMin']);
  $timeMax = new \DateTime($data['timeMax']);

  $freebusy->setTimeMin($timeMin->format(\DateTime::ISO8601));
  $freebusy->setTimeMax($timeMax->format(\DateTime::ISO8601));
  $freebusy->setTimeZone('America/Chicago');
		

  foreach($data['calendars'] as $calendarId) {
    $freebusyItem = new \Google_Service_Calendar_FreeBusyRequestItem();
    $freebusyItem->setId($calendarId);
    $freebusy->setItems(array($freebusyItem));
    $freebusyItems[] = $freebusyItem;
  }

  $freebusy->setItems($freebusyItems);

  $freebusyResponse = $service->freebusy->query($freebusy);

  $response['data'] = $freebusyResponse->toSimpleObject();
  $response['params'] = $data;

  return $response;
}

I hope this post be very helpful to you, please, share and comment ;)

Show Comments

Get the latest posts delivered right to your inbox.