Created
July 25, 2012 18:33
-
-
Save simukti/3177752 to your computer and use it in GitHub Desktop.
Simukti\Service\ShortUrl\Googl
This file contains 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 | |
/** | |
* Description of Googl | |
* | |
* @author Sarjono Mukti Aji <me@simukti.net> | |
*/ | |
namespace Simukti\Service\ShortUrl; | |
class Googl extends \Zend_Service_ShortUrl_AbstractShortener | |
{ | |
/** | |
* Url shortener endpoint | |
* | |
* @var string | |
*/ | |
protected $_urlApi = 'https://www.googleapis.com/urlshortener/v1/url'; | |
/** | |
* Base uri for short url validation | |
* | |
* @var string | |
*/ | |
protected $_baseUri = 'http://goo.gl'; | |
/** | |
* Google apiKey for url short request | |
* | |
* @var string | |
* @link https://developers.google.com/url-shortener/v1/getting_started#APIKey | |
*/ | |
static protected $apiKey; | |
/** | |
* @param string $apiKey | |
*/ | |
public function __construct($apiKey) | |
{ | |
if(null === self::$apiKey) { | |
self::setApiKey($apiKey); | |
} | |
} | |
/** | |
* @param string $apiKey | |
*/ | |
static public function setApiKey($apiKey) | |
{ | |
if(null === self::$apiKey) { | |
self::$apiKey = $apiKey; | |
} | |
} | |
/** | |
* @return string | |
* @throws \Zend_Service_ShortUrl_Exception | |
*/ | |
static public function getApiKey() | |
{ | |
if(null === self::$apiKey) { | |
throw new \Zend_Service_ShortUrl_Exception('Google API key was not provided.'); | |
} | |
return self::$apiKey; | |
} | |
/** | |
* @param string $url | |
* @return \Zend_Json JSON result | |
*/ | |
public function shorten($url) | |
{ | |
$this->_validateUri($url); | |
$client = self::getHttpClient(); | |
$client->resetParameters(true) | |
->setUri(sprintf("%s?key=%s", $this->_urlApi, self::getApiKey())) | |
->setHeaders('Content-Type: application/json') | |
->setRawData(\Zend_Json::encode(array('longUrl' => $url))) | |
->setMethod(\Zend_Http_Client::POST); | |
$response = $client->request(); | |
if($response->isSuccessful()) { | |
$result = \Zend_Json::decode($response->getBody()); | |
return $result['id']; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @param string $url | |
* @return array JSON result | |
*/ | |
public function unshorten($url) | |
{ | |
$this->_validateUri($url); | |
$this->_verifyBaseUri($url); | |
$client = self::getHttpClient(); | |
$client->resetParameters(true) | |
->setUri($this->_urlApi) | |
->setParameterGet(array( | |
'shortUrl' => $url, | |
'key' => self::getApiKey() | |
)) | |
->setMethod(\Zend_Http_Client::GET); | |
$response = $client->request(); | |
return $response->getBody(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment