2
\$\begingroup\$

I'm playing with a simple (for now) project in PHP with Google Calendar API. I have posted the code here in order to improve my programming style about whatever you think it's worth suggesting. Thank you.

As you can see, at the moment the script listEvents.php retrieves all the events in the last 7 days from primary calendar, and deletes the events whose title is included in the array deletable.

Below is the code so far:

listEvents.php

<?php

require_once (__DIR__."/beAuthorized.php");
require_once (__DIR__."/calConfig.php");

$beAuthorized = new beAuthorized();
$calConfig = calConfig::getInstance();

$deletable = $calConfig->getDeletable();
$calendarId = $calConfig->getCalendarId();

$optParams = array(
  'orderBy' => 'startTime',
  'singleEvents' => true,
  'timeMin' => date('Y-m-d\TH:i:sP', strtotime('-7 days')),
  'timeMax' => date('c'),
);

try {
    $service = $beAuthorized->getService();
    $results = $service->events->listEvents($calendarId, $optParams);
    $events = $results->getItems();
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

if (!empty($events)) {
    foreach ($events as $event) {
        if (in_array($event->getSummary(), $deletable)) {
               $service->events->delete($calendarId, $event->getId());
        }
    }
}

beAuthorized.php

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

class beAuthorized
{
     /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    private function getClient()
    {
        $client = new Google_Client();
        $client->setApplicationName('calendar-utilities');
        $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
        $client->addScope(Google_Service_Calendar::CALENDAR);
        $client->addScope(Google_Service_Calendar::CALENDAR_EVENTS);
        $client->setAuthConfig('credentials.json');
        $client->setAccessType('offline');
        $client->setPrompt('select_account consent');

        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = 'token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->setAccessToken($accessToken);
        }

        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));

                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                $client->setAccessToken($accessToken);

                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
                }
            }
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            }
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        }
        return $client;
    }

    /**
    * Returns a service object.
    */
    public function getService() 
    {
        // Get the API client and construct the service object.
        $client = $this->getClient();
        $service = new Google_Service_Calendar($client);
        return $service;
    }
}

calConfig.php

<?php

require_once (__DIR__."/singleton.php");

class calConfig extends singleton
{
    private $calendarId;
    private $deletable;

    protected function __construct()
    {
          if(!isset($this->calendarId)) {
               $this->calendarId = 'primary';
          }

          if(!isset($this->deletable)) {
              $this->deletable = array('Test', 'bye', 'one');
          }
    }

     public function getCalendarId() {
         return $this->calendarId;
     }      

     public function getDeletable() {
          return $this->deletable;
     }
}

singleton.php

<?php

class singleton
{
    private static $instances = [];
    protected function __construct() { }
    protected function __clone() { }

    public function __wakeup()
    {
        throw new \Exception("Cannot unserialize singleton");
    }

    public static function getInstance()
    {
        $subclass = static::class;
        if (!isset(self::$instances[$subclass])) {
            self::$instances[$subclass] = new static;
        }
        return self::$instances[$subclass];
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.