<?php
class Zend_Service_Digg extends Zend_Rest_Client
{
protected $_uri = 'http://services.digg.com/';
protected $_params = array();
protected $_responseType = 'xml';
protected $_responseTypes = array('php', 'xml', 'json');
public function __construct()
{
$this->setUri($this->_uri);
$client = self::getHttpClient();
$client->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
}
public function setParams($params)
{
// Validate mandatory parameters to endpoint
if (!isset($params['appkey']) || !isset($params['appkey'])) {
throw new Zend_Service_Digg_Exception('Param appkey missing');
}
foreach ($params as $key => $value) {
switch (strtolower($key)) {
case 'type':
$this->setResponseType($value);
break;
default:
$this->_params[$key] = $value;
break;
}
}
return $this;
}
public function getParams()
{
return $this->_params;
}
public function setResponseType($responseType)
{
if (!in_array(strtolower($responseType), $this->_responseTypes)) {
throw new Zend_Service_Digg_Exception('Invalid Response Type');
}
$this->_responseType = strtolower($responseType);
return $this;
}
public function getResponseType()
{
return $this->_responseType;
}
public function sendRequest($requestType, $path)
{
$requestType = ucfirst(strtolower($requestType));
if ($requestType !== 'Post' && $requestType !== 'Get') {
throw new Zend_Service_Digg_Exception('Invalid request type: ' . $requestType);
}
try {
$requestMethod = 'rest' . $requestType;
$response = $this->{$requestMethod}($path, $this->getParams());
return $this->formatResponse($response);
} catch (Zend_Http_Client_Exception $e) {
throw new Zend_Service_Digg_Exception($e->getMessage());
}
}
public function formatResponse(Zend_Http_Response $reposne)
{
if ('json' === $this->getResponseType()) {
return $response->getBody();
} elseif ('php' === $this->getResponseType()) {
return unserialize($response->getBody());
} else {
return new Zend_Rest_Client_Result($response->getBody());
}
}
public function fetchPopularStoriesByTopic($topic, array $params = array())
{
$this->setParams($params);
$path = sprintf('/stories/topic/%s/popular/', trim(strtolower($topic)));
return $this->sendRequest('GET', $path);
}
}