Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 83
GoogleAPIService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 7
420.00
0.00% covered (danger)
0.00%
0 / 83
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 __clone
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 getInstance
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 5
 addGoogleApiAccessToken
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 26
 getLastCreatedAccessToken
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 18
 shareFile
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 19
 getGoogleApiClient
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 11
<?php
namespace com\linways\core\ams\professional\service;
use com\linways\core\ams\professional\exception\ProfessionalException;
use com\linways\core\ams\professional\request\AddGoogleApiAccessTokenRequest;
use com\linways\core\ams\professional\request\GetPublicUrlRequest;
use com\linways\core\ams\professional\request\ShareGoogleDriveFileRequest;
/**
 *
 * @Date 20/04/20
 * @author  JithinVijayan <jithin@linways.com>
 */
class GoogleAPIService extends BaseService
{
    /**
     * Presence of a static member variable
     *
     * @var null
     */
    private static $_instance = null;
    /**
     * Mapper variable
     * @var array
     */
    private $mapper = [];
    /**
     * Initialise mapper, logger, hooks here
     *
     * ReportGenderService constructor.
     */
    private function __construct()
    {
//        $this->mapper = MapperService::getInstance()->getMapper();
    }
    /**
     * Prevent any object or instance of that class to be cloned
     */
    private function __clone()
    {
    }
    /**
     * Have a single globally accessible static method
     *
     * @return GoogleAPIService|null
     */
    public static function getInstance()
    {
        if (!is_object(self::$_instance))
            self::$_instance = new self ();
        return self::$_instance;
    }
    /**
     * Storing google api access tokens
     *
     * @param AddGoogleApiAccessTokenRequest $request
     * @return Object
     * @throws ProfessionalException
     */
    public function addGoogleApiAccessToken(AddGoogleApiAccessTokenRequest $request)
    {
        $request = $this->realEscapeObject($request);
        if (!empty($request->expirationTime)) {
            $request->expirationTime = date('Y-m-d H:i:s', $request->expirationTime);
        }
        if (empty($request->userId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_ID, "Invalid user details given");
        }
        if (empty($request->userType)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_TYPE, "Invalid user details given");
        }
        if (empty($request->feature)) {
            throw new ProfessionalException(ProfessionalException::INVALID_REQUEST, "Google feature not mentioned");
        }
        if (empty($request->accessToken)) {
            throw new ProfessionalException(ProfessionalException::INVALID_REQUEST, "Invalid access token given");
        }
        $sql = "INSERT INTO google_api_access_tokens (user_id, user_type, feature, access_token, created_date, expiration_date) 
                VALUES ($request->userId,'$request->userType','$request->feature','$request->accessToken',UTC_TIMESTAMP(),
                        '$request->expirationTime')";
        try {
            return $this->executeQueryForObject($sql, true);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Returns last created token of user
     *
     * @param $userId
     * @param $userType
     * @return string
     * @throws ProfessionalException
     */
    public function getLastCreatedAccessToken($userId, $userType)
    {
        $userId = (int)$this->realEscapeString($userId);
        $userType = $this->realEscapeString($userType);
        if (empty($userId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_ID, "Invalid user details given");
        }
        if (empty($userType)) {
            throw new ProfessionalException(ProfessionalException::INVALID_USER_TYPE, "Invalid user details given");
        }
        $sql = "SELECT access_token as token FROM google_api_access_tokens 
                WHERE user_type = '$userType' AND user_id = $userId AND CURRENT_TIMESTAMP()<expiration_date 
                ORDER BY created_date DESC";
        try {
            return $this->executeQueryFOrObject($sql)->token;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Sharing google drive files
     *
     * @param ShareGoogleDriveFileRequest $request
     * @return \Google_Service_Drive_Permission
     * @throws ProfessionalException
     */
    public function shareFile(ShareGoogleDriveFileRequest $request)
    {
        $request = $this->realEscapeObject($request);
        if (empty($request->documentId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_DOCUMENT_ID, "Invalid document details given");
        }
        try {
            $client = $this->getGoogleApiClient($request->userId, $request->userType);
            $service = new \Google_Service_Drive($client);
            $permission = new \Google_Service_Drive_Permission();
            $permission->setType($request->permission);
            $permission->setRole($request->role);
            return $service->permissions->create($request->documentId, $permission);
        } catch (\Exception $e) {
            if ($e->getCode() === 403) {
                throw new ProfessionalException(ProfessionalException::INSUFFICIENT_PERMISSION, "You dont have enough permission to make this file publicly available.");
            }
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $userId
     * @param $userType
     * @return \Google_Client
     * @throws ProfessionalException
     */
    private function getGoogleApiClient($userId, $userType)
    {
        $clientId = $GLOBALS['GDRIVE_CLIENT_ID'];
        $developerKey = $GLOBALS['GDRIVE_DEVELOPER_KEY'];
        $accessToken = $this->getLastCreatedAccessToken($userId, $userType);
        $client = new \Google_Client();
        $client->setScopes(\Google_Service_Drive::DRIVE);
        $client->setClientId($clientId);
        $client->setDeveloperKey($developerKey);
        $client->setAccessToken($accessToken);
//        $client->setAccessType('online');
//        if ($client->isAccessTokenExpired()) {
//            throw new ProfessionalException(ProfessionalException::ACCESS_TOKEN_EXPIRED, "Your access token is expired. Login with google to continue this process");
//        }
        return $client;
    }
}