Created
August 29, 2018 17:19
-
-
Save kevyworks/2d11a9ce230e2e12e11093e9dfac0af8 to your computer and use it in GitHub Desktop.
GoogleUrlApi Simple Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class GoogleUrlApi | |
*/ | |
class GoogleURLAPI | |
{ | |
/** | |
* GoogleUrlApi constructor. | |
* @param $key | |
* @param string $apiURL | |
*/ | |
public function __construct($key, $apiURL = 'https://www.googleapis.com/urlshortener/v1/url') | |
{ | |
// Keep the API Url | |
$this->apiURL = $apiURL . '?key=' . $key; | |
} | |
/** | |
* @param string $url | |
* @param array|null $curl_option | |
* @return mixed|bool | |
* @throws \Exception | |
*/ | |
public function shorten($url, array $curl_option = null) | |
{ | |
// Send information along | |
$response = $this->send($url, true, $curl_option); | |
if (isset($response['id'])) { | |
return $response; | |
} | |
if (isset($response['error'])) { | |
$error = $response['error']; | |
throw new \Exception($error['message'], $error['code']); | |
} | |
return false; | |
} | |
/** | |
* @param string $url | |
* @param array|null $curl_option | |
* @return mixed|bool | |
* @throws \Exception | |
*/ | |
public function expand($url, array $curl_option = null) | |
{ | |
// Send information along | |
$response = $this->send($url, false, $curl_option); | |
if (isset($response['longUrl'])) { | |
return $response; | |
} | |
if (isset($response['error'])) { | |
$error = $response['error']; | |
throw new \Exception($error['message'], $error['code']); | |
} | |
return false; | |
} | |
/** | |
* @param string $url | |
* @param bool $shorten | |
* @param array|null $curl_option | |
* @return mixed | |
*/ | |
public function send($url, $shorten = true, array $curl_option = null) | |
{ | |
// Create cURL | |
$ch = curl_init(); | |
// If we're shortening a URL... | |
if ($shorten) { | |
curl_setopt($ch, CURLOPT_URL, $this->apiURL); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("longUrl" => $url))); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); | |
} else { | |
curl_setopt($ch, CURLOPT_URL, $this->apiURL . '&shortUrl=' . $url); | |
} | |
if ($curl_option !== null) { | |
foreach ($curl_option as $opt => $val) { | |
curl_setopt($ch, $opt, $val); | |
} | |
} | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
// Execute the post | |
$result = curl_exec($ch); | |
// Close the connection | |
curl_close($ch); | |
// Return the result | |
return json_decode($result, true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment