I knocked this together in a few hours as I was just simply bored. I was going to add a namespace to this but decided there was no point.
This is also available on Github
All feedback is appreciated!
<?php
/**
* This class will allow you to generate goo.gl links
* @package Google
* @subpackage Googl
* @author Lloyd Davies
* @version 1.1.0
*/
class Googl
{
/**
* @const (string) API_KEY
* This constant stores the Google API key
*/
const API_KEY = "YOUR_GOOGLE_API_KEY";
/**
* @const (string) API_URL
* This is the Google API URL to be used with predefined placeholder (%s)
*/
const API_URL = "https://www.googleapis.com/urlshortener/v1/url?key=%s";
/**
* @const (boolean) DEBUG
* A boolean value to indicate to display errors/exceptions
*/
const DEBUG = true;
/**
* @const (string, array) ERROR_CODES
* Source: https://developers.google.com/drive/v3/web/handle-errors
* Stores a friendly defonition for error codes
*/
const ERROR_CODES = [
400 => 'Error: Missing required parameters, most likely key',
401 => 'Error: Invalid API key',
403 => 'Error: Daily limit exceeded',
500 => 'Error: Internal Google API error'
];
/**
* @var (string) largeURL
* This is the URL which is going to be converted
*/
public $largeURL = null;
/**
* __construct
* Magic method to inititate our class
* Check that the environment is suitable
*/
public function __construct($targetURL = null)
{
(!is_null($targetURL)) ? $this->largeURL = $targetURL : null;
if (!function_exists("curl_init"))
{
throw new Exception("Error -> the PHP cURL library is not installed", 1);
} elseif (empty(self::API_KEY) || strlen(self::API_KEY) !== 39)
{
throw new Exception("Error -> invalid Google API key", 1);
}
}
/**
* Generate
* This will return the shortend URL
* @return (string) - the shortend long URL
*/
public function Generate()
{
$getResponse = $this->postRequest(
$this->generateURL(),
$this->createJSON($this->largeURL)
);
$json = json_decode($getResponse, true);
if($this->errorExists($json))
{
$errorCode = (int)$json['error']['errors']['code'];
if(self::DEBUG)
{
throw new Exception($this->getFriendlyErrorCode($errorCode), 1);
}
} else {
return $json['id'];
}
}
/**
* createJSON
* Will create the JSON payload needed to send to Google
* @return (string) the serialized JSON string
* @param (string) $longURL - the URL to be converted
*/
private function createJSON($longURL)
{
return json_encode([
'longUrl' => $longURL
]);
}
/**
* postRequest
* This will create a new cURL instance and inititate a POST request
* @return (string) the response from the request
* @param (string) $url - the URL to be requested
* @param (string, array) $data - the POST data
*/
private function postRequest($url, $data)
{
try
{
$ch = curl_init();
$options = [
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HEADER => 0,
CURLOPT_TIMEOUT => 10,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
];
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
return $response;
} catch (Exception $e) {
if(self::DEBUG)
{
throw new Exception(
$e->getMessage(),
$e->getCode()
);
}
}
}
/**
* generateURL
* This will generate the API URL to be used in the POST request
* @return (string) - the generated URL
*/
private function generateURL()
{
return sprintf(
self::API_URL,
self::API_KEY
);
}
/**
* getFriendlyErrorCode
* @param (int) $errorCode - the error code returned
* @return (string) - the friendly error message
*/
private function getFriendlyErrorCode($errorCode)
{
return (array_key_exists(self::ERROR_CODES, $errorCode)) ? self::ERROR_CODES[$errorCode] : "Undefined error";
}
/**
* errorExists
* @param (string, array) $jsonArray - the JSON object
* @return (bool) - if it exists or not
*/
private function errorExists($jsonArray)
{
return array_key_exists('error', $jsonArray);
}
}